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
JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function. They all have Function Scope: function myFunction() {
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
var is called as function scope that is if a variable is declared using var keyword it will be accessible throughout the function. let & const are also called as block scope that is they are accessible within that particular block.
Global Scope and Local ScopeVariables defined inside a function are in the local scope . They have a different scope for every call of that function. This means that variables having the same name can be used in different functions.
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:
this
keyword in bar
function is bound to foo
objectIn 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.bar
to foo.bar
, but the parenthesis causes the assigned function to be returned, and then executed.
(foo.bar = foo.bar)();
//is the same as
var f = (foo.bar = foo.bar);
f();
//and this also the same as:
var f= foo.bar;
f();
The function returned from parenthesis is not bound to anything, so this
will refer to global object, in case of browsers - to the window
object.
4.. The clause (foo.bar, foo.bar)() is just alike:
a = (3, 4); //last value is returned, first just parsed.
//a contains 4
var f = (foo.bar, foo.bar);
//f contains body of foo.bar function,
f() // is executed in the context of `global` object, eg. `window`.
Please read about binding
of functions in JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With