var self = this?

后端 未结 8 1373
失恋的感觉
失恋的感觉 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:40

    I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

     $('#foobar').ready('click', this.doSomething.bind(this));
    

    The bind method returns a new function that calls the original method with the scope you have specified.

提交回复
热议问题