Javascript lost context when assigned to other variable

后端 未结 4 990
一向
一向 2020-11-30 13:28

Why in javascript if you reference objects method to some variable it loses that objects context. Can\'t find any link with explanation what happens under the hood. Except t

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 13:36

    It becomes clear when you print the object and the reference to the function:

    console.log(obj); // Prints -> Class {property: 1, method: function}
    
    console.log(refToMethod);
    // Prints 
    // function () {
    //    return this.property;
    // }
    

    In the context of the obj, what is this? It is the Class object, that has an attribute called property.

    And what is this in the context of the refToMethod? It is the window object. Thats why your assert failed the first time and it is true the second time. When you declare:

    var property = 1;
    

    You are actually declaring an attribute to the window object.

提交回复
热议问题