Class methods as event handlers in JavaScript?

前端 未结 4 1125
予麋鹿
予麋鹿 2020-11-29 00:59

Is there a best-practice or common way in JavaScript to have class members as event handlers?

Consider the following simple example:


            


        
4条回答
  •  悲哀的现实
    2020-11-29 01:49

    You can use fat-arrow syntax, which binds to the lexical scope of the function

    function doIt() {
      this.f = () => {
        console.log("f called ok");
        this.g();
      }
      this.g = () => {
        console.log("g called ok");
      }
    }
    

    After that you can try

    var n = new doIt();
    setTimeout(n.f,1000);
    

    You can try it on babel or if your browser supports ES6 on jsFiddle.

    Unfortunately the ES6 Class -syntax does not seem to allow creating function lexically binded to this. I personally think it might as well do that. EDIT: There seems to be experimental ES7 feature to allow it.

提交回复
热议问题