var foo = {
bar: function () {
alert(this);
}
};
foo.bar(); // Reference, OK => foo (1)
(foo.bar)(); // Reference, OK => foo (2)
(foo.bar = foo.bar)(); // global? (3)
Can you explain why the results of (2) and (3) are different?
var temp =foo.bar=foo.bar;
temp();
Continuous assignment
Understand?
Because this is not called as an object method but as a function call, so this points to undefined, and in non-strict mode undefined points to the global world.
This is defined by the context during execution, so naturally whoever calls this is who
The call in (2) is foo.bar, then this this has found the foo object;
When calling (3), there is an assignment first, and foo.bar is assigned to foo.bar, so that it becomes a global variable. This function is called globally, so of course it points to undefined (non-strict mode in the browser environment).
Judging from the code comments, the questioner may just not understand (3). Here is the explanation:
foo.bar = foo.bar
The expression returns an anonymous function, that is,function( ) {alert(this);}
.foo.bar = foo.bar
表达式返回的是匿名函数,即function() {alert(this);}
。所以再调用相当于该匿名函数的自调用,即
(function() {alert(this);})();
So the call is equivalent to the self-call of the anonymous function, that is,(function() {alert(this);})();
.Addition:
(foo.bar)
The expression returns what is in parentheses, that is,foo.bar
. Thenfoo.bar
is called as a function, i.e.foo.bar()
.(foo.bar)
表达式返回小括号里的,即foo.bar
。然后foo.bar
作为函数被调用,即foo.bar()
。而赋值表达式是将右侧的即
foo
对象的bar
The assignment expression assigns the value stored in thebar
of thefoo
object on the right side to the left side and returns it.var foo = {
bar: function () {
}
};
(foo.bar)(); // Reference, OK => foo (2)
Note: (foo.bar)() here is equivalent to the first foo.bar(), What is executed is the bar method in the foo object. This points to the foo object
(foo.bar = foo.bar)(); // global? (3)
Note: First look at foo.bar = foo.bar, foo .bar is function () {alert(this);} assigned to foo.bar, then (foo.bar = foo.bar) is equal to (function(){alert(this)}), then add the outside () is an immediate function:
(function(){alert(this)})(); so what it points to here is the global window.
The assignment expression returns the global =》window
foo.bar is assigned function(){alert(this)} this points to window globally