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
?
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
).