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

后端 未结 4 1658
挽巷
挽巷 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条回答
  •  粉色の甜心
    2021-02-04 12:05

    It may help to think of the dot operator as behaving similarly to a with statement. When you run foo.bar(), the result is much the same as if you ran:

    with (foo) {
        bar(); // returns 20
    }
    

    This will run your bar function with foo overlaid on top of the global object, allowing it to find the x in foo and thus return 20.

    If you don't call bar immediately, though, as in (foo.bar = foo.bar), you instead get:

    with (foo) {
        bar; // returns "bar" itself
    }
    

    The result is then passed out of the parentheses, producing an intermediate statement like (), which has no dot operator, so no with statement, so no access to foo, just to the global value of x.

    (The dot operator doesn't actually convert to a with statement, of course, but the behavior is similar.)

提交回复
热议问题