From what I have read and understood, execution context(this) of a function has nothing to do with where its declared, but from where it was invoked (call site). Consider 2 cases, where foo is defined in global context-
//1.
function foo(){ console.log(this); }
var obj = {
x: foo,
};
obj.x(); //prints obj because foo was called "on" obj object
//2.
function foo(){ return this; }
var obj = {
x: function(){ console.log(foo()); },
};
obj.x(); //prints window object.
I have confusion in 2nd case. Though I understand context for x function is obj, I can't comprehend how come foo was called on window object from within x function (whose context is in fact obj)? Am sure there are numerous questions on this topic, I was unable to find something similar to this kind of example. Thanks.