Why does the assignment operator return a value and not a reference?

后端 未结 4 1655
挽巷
挽巷 2021-02-04 12:04

I saw the example below explained on this site and thought both answers would be 20 and not the 10 that is returned. He wrote that both the comma and assignment returns a value,

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 12:15

    You're misunderstanding it.

    Both examples are returning the window's x property, since they aren't being directly invoked on foo.

    The value of the this keyword inside a function depends on the context in which the function was called.

    In an ordinary function call (eg, myFunc()), this will be the global object, which is usually window.
    In an object method call (eg, foo.bar()), this will be the object on which the function was invoked. (in this case, foo)

    You can set the context explicitly by calling myFunc.call(context, arg1, arg2) or myFunc.apply(context, argArray).

    Both of your examples are normal invocations of an expression that evaluates to foo.bar.
    Therefore, this is the window.

    They are equivalent to

    var func = (some expression);
    func();
    

提交回复
热议问题