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,
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.)