This context changes upon assignment.

This question is from ECMA-262 quiz

var x = 100; var foo = { x: 50, bar: function(){ return this.x; } } console.log(foo.bar()); //returns 50 console.log((foo.bar = foo.bar)()); //returns 100 

How does the this context change in the second console expression? or in general, what object matters (assignment), returns a global object?

+4
source share
2 answers

foo.bar (operator ) evaluates the reference "property" bar "on the object", and this will be considered special if it is called .

(foo.bar = foo.bar) ( assignment ) just gives the assigned value, and calling it will cause the global object to be used like this .

+3
source

foo.bar = foo.bar returns the function foo.bar , which is then called via (...)() . Since the function was not called as a property of the foo object, its this will not be the foo object, but rather in this case a global object.

+2
source

All Articles