最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript object functions and `this` when unbound and returned in expressionparens - Stack Overflow

programmeradmin4浏览0评论

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

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
Share Improve this question edited Apr 11, 2015 at 16:57 AstroCB 12.4k20 gold badges59 silver badges74 bronze badges asked Apr 11, 2015 at 16:31 TomFuertesTomFuertes 7,2705 gold badges36 silver badges49 bronze badges 1
  • 1 As I understand it, there is, between (foo.bar) and foo.bar(line 2) no difference. Its just inserting unnecessary brackets like ` 1 + 2 * 3 ` is the same as ` 1 + ( 2 * 3 ) ` – Dustin Hoffner Commented Apr 11, 2015 at 16:54
Add a ment  | 

2 Answers 2

Reset to default 9

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.

发布评论

评论列表(0)

  1. 暂无评论