对象文本中的范围链

Scope chains in object literals

本文关键字:范围 文本 对象      更新时间:2023-09-26
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的范围解析checkVarsassign跳过对象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

换句话说,您的困惑与范围解析没有任何关系。 每当您引用 x 时,您都指的是您在程序顶部定义的名为x的唯一变量。 每次引用 this.x 时,您都指的是在mod对象文本上定义的名为x的属性。

希望这有助于澄清事情!

变量和对象属性不是一回事。变量是作用域链的一部分,属性不是。assigncheckVars范围内的唯一变量是 xmodmod的属性只能通过this.propName(或mod.propName(从这些方法中可见。