why 'this' point to 'window' obj when using assignment operator in iife?

梦想与她 提交于 2019-12-12 09:55:40

问题


I was wondering why the example will return 'global' not 'obj2'? And what's different between '(obj2.say = obj1.say)()' and '(obj2.say)()'? Here is the code:

var text = 'global';
var obj1 = { text: 'obj1', say: function () {console.log(this.text)}};
var obj2 = { text: 'obj2'};
(obj2.say = obj1.say)();

回答1:


The result of an assignment is the value that was assigned. Example:

var foo, bar;
foo = (bar = 42);
console.log(foo); // 42

Hence when you do (obj2.say = obj1.say), the result of the assignment, was returned by the grouping operator, is the function object in obj1.say.

The whole expression to be be equivalent to

var result = obj2.say = obj1.say;
result();

And when a function is called the "normal" way (func()), this refers to the global object or is undefined in strict mode.


(obj2.say)() is quite special actually. The grouping operator alone does not resolve (internal) references to values. I.e. the result of obj2.say is, internally, a reference that describes the member access say on obj2. The grouping operator, (...) returns that reference unchanged, not resolving it to the actual function object. That's why this will correctly point to obj2. Omitting the grouping operator has the same effect.

This is actually called out in the spec:

This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesized expressions.




回答2:


Because the value of (obj2.say = obj1.say) is a plain Function object, while obj2.say() is a method call with obj2.




回答3:


(obj2.say)() will just call the say function from obj2.

(obj2.say = obj1.say)() will assign obj1.say to obj2.say and then call it.

I am not sure about the this.text - I'm hoping someone can help with that - even I am curious to find that out.



来源:https://stackoverflow.com/questions/45558692/why-this-point-to-window-obj-when-using-assignment-operator-in-iife

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!