为什么'this'指向'window'obj在生活中使用赋值运算符? [英] why 'this' point to 'window' obj when using assignment operator in iife?
问题描述
我想知道为什么这个例子会返回'global'而不是'obj2'? '(obj2.say = obj1.say)()'和'(obj2.say)()'之间有什么不同?
以下是代码:
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)();
推荐答案
<分配的em> result 是已分配的值。示例:
The result of an assignment is the value that was assigned. Example:
var foo, bar;
foo = (bar = 42);
console.log(foo); // 42
因此当你做时(obj2.say = obj1.say )
,分配的结果,由分组运算符返回,是 obj1.say
中的函数对象 。
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
.
整个表达式等于
var result = obj2.say = obj1.say;
result();
当一个函数被称为正常方式时( func()
), 此
指的是全局对象或是未定义
在严格模式下。
And when a function is called the "normal" way (func()
), this
refers to the global object or is undefined
in strict mode.
(obj2.say)()
实际上非常特别。仅分组运算符不会解析(内部)对值的引用。即 obj2.say
的结果在内部是一个描述成员访问的引用在
> OBJ2
。分组运算符(...)
返回该引用不变,而不是将其解析为实际的函数对象。这就是这个
将正确指向 obj2
的原因。省略分组运算符具有相同的效果。
(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.
这实际上是在规范中调出:
此算法不具备申请
GetValue
评估表达式的结果。这样做的主要动机是,delete
和typeof
等运算符可以应用于带括号的表达式。
This algorithm does not apply
GetValue
to the result of evaluating Expression. The principal motivation for this is so that operators such asdelete
andtypeof
may be applied to parenthesized expressions.
这篇关于为什么'this'指向'window'obj在生活中使用赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!