ECMAScript 中访问器 属性 和数据 属性 之间的区别?

Difference between accessor property and data property in ECMAScript?

ECMAScript 版本 5 规范引入了一种称为访问器属性的新型属性。与称为数据属性的现有已知属性类型相比,仅就规范而言,这两者之间有何关联?

我已经阅读了 ECMAScript v5 的规范,但我不清楚确切的区别。有人可以用代码示例解释这两者吗?我在网上搜索过,但所有的例子似乎都含糊不清。

命名数据属性 将名称与值相关联。这意味着您可以使用 属性 直接获取和检索数据,例如 class.

上的 public 字段

命名访问器属性 将一个名称与一个或两个访问器函数相关联。 访问器函数用于存储或检索与 属性 关联的值。这意味着您限制对 get or/and set 访问器 属性.

后面的某个值的访问

比较两者,第一个选项没有提供任何封装或控制来访问您的值。第二个让您指定您的值是否可以读取 'get accessor'、写入 'set accessor' 或两者。

更新

关于您的次要疑问(在评论中),这里是关于我刚刚编写的 Ecma 脚本基础知识的快速 101 ;):

// accounting namespace
var Accounting = {};

// client class definition
Accounting.Client = function(){
    // private fields
    var _address="";
    var _phone=0;

    // data property
    this.token = "";

    // privileged properties
    Object.defineProperty(this, "address", {
        get: function(){
            if(console) console.log('hey im using get address accessor property.');        
            return _address;
        },
        set: function(value){
            if(console) console.log('hey im using set address accessor property.');

            if(value == null)
                throw new Error('Field address cannot be null!');

            _address=value;
        }
    });

    Object.defineProperty(this, "phone", {
        get: function(){
            if(console) console.log('hey im using get phone accessor property.');
            return _phone;
        },
        set: function(value){
            if(console) console.log('hey im using set phone accessor property.');
            _phone=value;
        }
    });
};

Accounting.Client.prototype = {
    sayHello: function(){
        alert("hello im a shared function, which means im shared by all objects of type Client"
              + " and i do not have access to private fields :(.");
    }
};


/* use case */
var c1 = new Accounting.Client();
c1.address = "Rua da Capela";
c1.phone = 961909090;
c1["token"] = "mytoken in a data property";
c1.token = c1.token + "-111";

alert("client address is '" + c1.address + "' and his phone also is '" + c1.phone + "'.");
c1.sayHello();    
alert(c1.token);

try{
    // check non nullable field.
    c1.address=null;
}
catch(ex){
    alert(ex);
}

用我的jsfiddle来玩!

编码愉快!