JavaScript对象函数和`this`在未绑定并在表达式/ parens中返回时 [英] JavaScript object functions and `this` when unbound and returned in expression/parens
问题描述
第1-2和4-5行在返回此
方面有意义。关于第3行,我错过了什么?我认为它会返回窗口
,类似于4-5行。是否还有另外一种模式可以帮助证明原因?
Lines 1-2 and 4-5 make sense in terms of the this
returned. What am I missing about line 3? I thought it would return window
similar to lines 4-5. Is there another pattern not in these 5 that could help demonstrate why?
foo = { bar : function () { return this } }
foo.bar() // ==> foo
(foo.bar)() // ==> foo / but why?
(foo.bar ? foo.bar : $.noop)() // ==> window
(foo.bar || 0)() // ==> window
推荐答案
分组运算符不会破坏属性引用,正在激发方法调用。
The grouping operator does not destroy property references, which are provoking the method call.
这在规范:
注意:此算法不适用 GetValue 到
评估Expression
的结果。这样做的主要动机是可以将
运算符(如delete
和typeof
)应用于带括号的
表达式。
NOTE: 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 parenthesised expressions.
在第4行和第5行中,它不是括号而是运算符(? :
和 ||
)取消引用该属性并生成未绑定函数。
In your lines 4 and 5, it's not the parenthesis but the operators (?:
and ||
) that de-reference the property and yield the "unbound" function.
这篇关于JavaScript对象函数和`this`在未绑定并在表达式/ parens中返回时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!