+ 2

explain this js code

var x = 3; var foo = { x : 2, baz : { x : 1, bar : function (){ return this.x; } } } var go = foo.baz.bar; document.write(go()); //outputs 3 document.write(foo.baz.bar()); //outputs 1 Can you please explain the concept behind this differing result?

16th Mar 2021, 6:41 AM
CHANDAN ROY
CHANDAN ROY - avatar
3 Respuestas
+ 6
Closures. This is a very good quiz actually. It brings out a very important concept of JavaScript, about Scopes of Variables go is declared as a function in global scope, so when go() is called, the `this` in this.x is referencing the x in global scope, so the value is 3. foo.baz.bar() is calling the function bar, it looks up the environment of bar(), and found an x in the scope of baz, so it returns the value of this scope, which is 1. It is very essential for a JavaScript developer to understand this concept called Closures. I would suggest readings provided by David Carroll : https://www.sololearn.com/post/45261/?ref=app The three readings are from simple to understand to thorough understanding, so be sure to read all three articles.
16th Mar 2021, 7:00 AM
Gordon
Gordon - avatar
0
in "strict mode" value of this inside function are either the object bound to it or null (instead of 'window' global object) to avoid accidentally accessing global variable (then go() will throw an error as null is not a valid object)
16th Mar 2021, 8:06 AM
visph
visph - avatar