javascript how to get this.variable in callback function

后端 未结 2 445
借酒劲吻你
借酒劲吻你 2021-01-13 23:34

In the following customized class in javascript, in callback, why does this.obj have nothing but local variable obj has thing I want? Thanks.

function Class         


        
2条回答
  •  借酒劲吻你
    2021-01-13 23:44

    As for this line of code:

    console.log(obj);  // this one has stuff
    

    The reason it works has to do with how JavaScript closure works. The code defined in your anonymous function has access to all variables in its local scope as well as variables defined in encompassing scopes and therefore obj is available. See How do JavaScript closures work? for more on closure.

    The keyword this however, is a reference to the current scope. Because you are accessing this.obj from within the anonymous function, this refers to the anonymous function itself - which has no obj property defined. In the enclosing function, which is extending the ClassTest prototype, this refers to the current ClassTest object, which does have a obj property defined.

提交回复
热议问题