Variables and object properties are not the same thing. Variables are part of scope chains, properties are not. The only variables in scope of assign
and checkVars
are x
and mod
. The properties of mod
are only visible from within those methods via this.propName
(or mod.propName
).
Scope chains in object literals [duplicate]
-
01-06-2022 - |
Question
var x = 9;
var mod = {
x: 81,
assign: function(){
this.x = 9;
x = 3;
},
checkVars: function(){
alert(x + " - " + this.x );
}
};
mod.checkVars(); //9 - 81
mod.assign();
mod.checkVars(); //3 - 9
alert(x); //3
Please explain how does scope chains set themselves here. And why does scope resolution for x
in checkVars
and assign
skip the object mod
?
Solution 2
OTHER TIPS
I've added some comments to your program:
var x = 9; // This is the *only* variable called x in your program
var mod = {
x: 81, // this x refers to a property of mod also called x
assign: function(){
this.x = 9; // "this" refers to the object mod, this.x is the x property of mod
x = 3; // x here refers to your variable called x
},
checkVars: function(){
alert(x + " - " + this.x ); // same as above
}
};
mod.checkVars(); //9 - 81
mod.assign();
mod.checkVars(); //3 - 9
alert(x); //3
In other words, your confusion doesn't have anything to do with scope resolution. Any time you reference x
, you're referring to the one and only variable called x
you defined at the top of your program. Any time you refer to this.x
, you're referring to the property called x
you defined on the mod
object literal.
Hope this helps clarify things!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow