javascript - js this question
PHP中文网
PHP中文网 2017-05-19 10:22:14
0
5
449
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?

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
世界只因有你

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.barThe 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. Then foo.bar is called as a function, i.e. foo.bar(). (foo.bar)表达式返回小括号里的,即foo.bar。然后foo.bar作为函数被调用,即foo.bar()
而赋值表达式是将右侧的即foo对象的barThe assignment expression assigns the value stored in the bar of the foo object on the right side to the left side and returns it.

曾经蜡笔没有小新

var foo = {
bar: function () {

alert(this);

}
};
(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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template