In Javascript, why is the “this” operator inconsistent?

后端 未结 8 1776
挽巷
挽巷 2020-11-22 15:04

In JavaScript, the \"this\" operator can refer to different things under different scenarios.

Typically in a method within a JavaScript \"object\", it refers to the

8条回答
  •  执念已碎
    2020-11-22 16:02

    If you're using a javascript framework, there may be a handy method for dealing with this. In Prototype, for example, you can call a method and scope it to a particular "this" object:

    var myObject = new TestObject();
    myObject.firstMethod.bind(myObject);
    

    Note: bind() returns a function, so you can also use it to pre-scope callbacks inside your class:

    callBack.bind(this);
    

    http://www.prototypejs.org/api/function/bind

提交回复
热议问题