Take a look at this snippet:
var obj = {
fn: function () {return this;}
};
var x = obj.fn;
obj.fn(); // returns obj
x(); // returns window (in the browser)
I’m curious why obj.fn() is different from x=obj.fn; x(). Is there a special case for attribute lookup directly followed by a function call within a single expression – or there is some more complex magic going on under the hood (like with descriptor protocol in Python) ?
The value from the
thiscontext variable always depends on how a function was invoked.will invoke the function as
method, which means itsthisvalue will always reference the containing object, in this caseobj.By directly storing a reference in
xthe function is called “just like that” in the global scope, which means it will always reference theglobal objectin non ES5-strict mode environment and it will beundefinedin ES5 strict mode.So, you always need to be careful when referencing object methods in variables. If such a method wants to access some data from its own object via
this.someProp, it will obviously fail ifthisis bound to another object/context.Disclaimer: “will always reference the containing object” is not entirely correct. If the function was bound to another object via
Function.prototype.bind(), it will always reference that bound object.