Who can explain why result are [20, 20, 10, 10] in this code:
var x = 10;
var foo = {
x: 20,
bar: function () {
var x = 30;
return this.x;
}
};
console.log(
foo.bar(),
(foo.bar)(),
(foo.bar = foo.bar)(),
(foo.bar, foo.bar)()
);
Links to specification are welcomed
Can’t point you at specification, but i can highly recommend reading Douglas Crockford’s “Javascript: The good parts”. This book will help you understand most of the weird but great features of JavaScript.
As of your question:
thiskeyword inbarfunction is bound tofooobjectIn javascript you can assign variables from right to left multiple times
z = 3;
x = (y = z);
console.log(x); //3
functions are variables as anything else. So you are assigning the function
foo.bartofoo.bar, but the parenthesis causes the assigned function to be returned, and then executed.The function returned from parenthesis is not bound to anything, so
thiswill refer to global object, in case of browsers – to thewindowobject.4.. The clause (foo.bar, foo.bar)() is just alike:
Please read about
bindingof functions in JavaScript.