Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对象文字中的作用域链_Javascript_Oop_Object_Scope Chain - Fatal编程技术网

Javascript 对象文字中的作用域链

Javascript 对象文字中的作用域链,javascript,oop,object,scope-chain,Javascript,Oop,Object,Scope Chain,请解释范围链是如何在这里设置的。为什么checkVars和assign中的x的范围解析会跳过对象mod?我在您的程序中添加了一些注释: var x = 9; var mod = { x: 81, assign: function(){ this.x = 9; x = 3; }, checkVars: function(){ alert(x + " - " + this.x ); } }; mod.check

请解释范围链是如何在这里设置的。为什么
checkVars
assign
中的
x
的范围解析会跳过对象
mod

我在您的程序中添加了一些注释:

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
换句话说,您的困惑与范围解析无关。无论何时引用
x
,都是指在程序顶部定义的唯一一个名为
x
的变量。任何时候引用
this.x
,都是指在
mod
对象文本上定义的名为
x
的属性


希望这有助于澄清问题

变量和对象属性不是一回事。变量是范围链的一部分,属性不是。
assign
checkVars
范围内的唯一变量是
x
mod
mod
的属性只能通过
this.propName
(或
mod.propName
)从这些方法中看到。

mod
没有名为
x
的变量。它有一个名为
x
的属性。我从来没有说过
x
是一个变量
checkVars
只是一个花哨的名字,如果你是认真的话。你似乎缺少的是范围链只适用于变量,而不适用于属性(原型链适用于这些变量)。@bfavareto你是对的。你做了一个很好的提示。
这个x指的是你的变量x
,也许你应该把它改成:
x这里指的是你的变量x
-只是为了消除关于“这个x”和
this.x
@NULL的任何误解-嘿,是的,这可能不那么容易混淆。实际上,正在进行一些范围解析。函数中没有本地
x
,并且在作用域链的父级中找到了
x
。@bfavaretto-嗯,我想人们会知道我的意思。但是我改变了措辞。是的,有时候我太挑剔了,甚至没有注意到。。。很抱歉。
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