根据返回的this,第1-2行和第4-5行是有意义的。3号线我遗漏了什么?我以为它会返回类似于第4-5行的window。难道这5中没有另一种模式可以帮助说明原因吗?
foo = { bar : function () { return this } }
foo.bar() // ==> foo
(foo.bar)() // ==> foo / but why?
(foo.bar ? foo.bar : $.noop)() // ==> window
(foo.bar || 0)() // ==> window发布于 2015-04-11 16:54:31
发布于 2015-04-11 17:02:13
foo.bar这里是一个匿名函数。
如果将其分成不同的行,可能会更有意义:
foo = {
bar: function() {
return this;
}
}所以,当你打电话给foo.bar时,你得到的是function() { return this; }。在第二行,直接调用该函数(foo.bar()),因此它返回this,对象的实例(foo)。
在第三行,您得到了相同的结果,因为您不仅要求匿名函数,而且还执行该函数:
(foo.bar); // (function() { return this; }); A reference to the function
(foo.bar)(); // (function() { return this; })(); Actually calling the function因为在后一种情况下,您正在执行函数,就像在第二行中那样,结果是相同的(foo)。
然而,在第4行和第5行中,正如Bergi所说的那样,您使用的操作符将它们从函数中取消引用,这将留给您一个Window对象,而不是foo。
https://stackoverflow.com/questions/29580252
复制相似问题