search

Home  >  Q&A  >  body text

javascript - <div onclick="fun()"></div> Is this kind of fun function only valid if it is written as a global function?

<p onclick="fun()"></p>

It seems that event functions can only be written in the global scope. What if I want to call methods in the class?

class xxx(){
    func(){}//如果要调用这个方法呢?不能直接写在onclick后面吧
}
欧阳克欧阳克2707 days ago687

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-06-30 10:01:44

    If you want to call a function in a class, you have to instantiate it

    let x = new xxx()
    <p onclick="x.fun()"></p>

    First of all, you have to understand that class is just syntactic sugar for the constructor, which is equivalent to

    var xxx = (function () {
        function xxx() {}
        xxx.prototype.func = function () { };
        return xxx;
    }());

    Uh, what does that () after class mean? New syntax?

    reply
    0
  • Cancelreply