Max*_* Ch 2 javascript oop object scope-chain
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
Run Code Online (Sandbox Code Playgroud)
请解释范围链如何在这里设置自己.为什么范围解析为xin checkVars和assignskip对象mod?
我在你的程序中添加了一些评论:
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
Run Code Online (Sandbox Code Playgroud)
换句话说,您的混淆与范围解析没有任何关系.无论何时引用x,您都指x的是在程序顶部定义的唯一一个变量.您提到的任何时候this.x,您指的是x在mod对象文字上定义的名为您的属性.
希望这有助于澄清事情!