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,
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();