第1-2行和第4-5行对于返回的this
有意义。我对第3行缺少什么?我认为它会返回window
,类似于第4-5行。这5个模式中是否还有其他模式可以帮助说明原因?
foo = { bar : function () { return this } }
foo.bar() // ==> foo
(foo.bar)() // ==> foo / but why?
(foo.bar ? foo.bar : $.noop)() // ==> window
(foo.bar || 0)() // ==> window
foo.bar
这是一个匿名函数。
如果将其分成不同的行,可能会更有意义:
foo = {
bar: function() {
return this;
}
}
因此,当您呼叫foo.bar
时,您会得到function() { return this; }
。在第二行,您直接调用该函数(foo.bar()
),因此它返回对象对象(this
)的实例foo
。
在第三行,您得到相同的结果,因为您不是only要求匿名函数,而是也要执行该函数:
(foo.bar); // (function() { return this; }); A reference to the function
(foo.bar)(); // (function() { return this; })(); Actually calling the function
因为在后一种情况下,您像在第二行中那样执行函数,所以结果是相同的(foo
)。
但是,正如Bergi所说,在第4和第5行中,您使用的运算符从函数中取消引用它们,这给您留下了Window
对象而不是foo
。