var self = this?

后端 未结 8 1560
失恋的感觉
失恋的感觉 2020-11-22 09:10

Using instance methods as callbacks for event handlers changes the scope of this from \"My instance\" to \"Whatever just called the callback\"

8条回答
  •  自闭症患者
    2020-11-22 09:46

    One solution to this is to bind all your callback to your object with javascript's bind method.

    You can do this with a named method,

    function MyNamedMethod() {
      // You can now call methods on "this" here 
    }
    
    doCallBack(MyNamedMethod.bind(this)); 
    

    Or with an anonymous callback

    doCallBack(function () {
      // You can now call methods on "this" here
    }.bind(this));
    

    Doing these instead of resorting to var self = this shows you understand how the binding of this behaves in javascript and doesn't rely on a closure reference.

    Also, the fat arrow operator in ES6 basically is the same a calling .bind(this) on an anonymous function:

    doCallback( () => {
      // You can reference "this" here now
    });
    

提交回复
热议问题