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!