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, not a reference. I don’t quite understand what that means.
I understand it in relation to passing variables into functions or methods i.e primitive types are passed in by value and objects by reference but I’m not sure how it applies in this case.
I also understand about context and the value of ‘this’ (after help from stackoverflow) but I thought in both cases I would still be invoking it as a method, foo.bar() which would mean foo is the context but it seems both result in a function call bar().
Why is that and what does it all mean?
var x = 10;
var foo = {
x: 20,
bar: function () {return this.x;}
};
(foo.bar = foo.bar)();//returns 10
(foo.bar, foo.bar)();//returns 10
It doesn’t have to do with values vs. references, it has to do with
thisvalues (as you suspected). In JavaScript,thisis set entirely by how a function is called, not where it’s defined. You set thethisvalue in one of three ways:obj.foo()) or bracketed notation (obj["foo"]()).withstatement (really just a variant of #1, but worth calling out separately, particularly as it’s not obvious from the source code)applyorcallfeatures of the function instance.In your examples above, you’re not doing any of those, so you end up calling the function with the default
thisvalue, the global object, and soxcomes from there rather than from yourfooobject. Here’s another way to think about what that code is doing:If you don’t directly use a property to actually make the call (instead retrieving the value of the property and then making the call with that), the
thishandling doesn’t kick in.