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

后端 未结 2 1180
予麋鹿
予麋鹿 2020-11-29 13:18

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.

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 13:41

    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.

提交回复
热议问题