JavaScript object functions and `this` when unbound and returned in expression/parens

浪子不回头ぞ 提交于 2019-11-27 16:04:32

The grouping operator does not destroy property references, which are provoking the method call.

This is explicitly mentioned in the spec:

NOTE: 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 parenthesised expressions.

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.

foo.bar here is an anonymous function.

It might make more sense if you split it up into different lines:

foo = {
    bar: function() {
        return this;
    }
}

So, when you call foo.bar, you're getting function() { return this; }. On line two, you call that function directly (foo.bar()), so it returns this, the instance of the object (foo).

On line three, you get the same result because you're not only asking for the anonymous function, but executing that function as well:

(foo.bar); // (function() { return this; }); A reference to the function
(foo.bar)(); // (function() { return this; })(); Actually calling the function

Because in the latter case, you're executing the function as you did in line two, the result is the same (foo).

In lines four and five, however, as Bergi said, the operators you use dereference them from the function, which leaves you with a Window object rather than foo.

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