rin*_*ord 9 javascript accessor ecmascript-5
ECMAScript版本5规范引入了一种称为访问器属性的新类型属性.与称为数据属性的现有和已知类型的属性相比,这两个事物如何仅在规范方面相互关联?
我已经阅读了ECMAScript v5的规范,我不清楚确切的区别.有人可以用代码示例解释这两个吗?我搜索过互联网,但所有的例子看起来都很模糊.
Joã*_*nho 12
命名数据属性将名称与值相关联.这意味着您可以使用该属性直接获取和检索数据,例如类上的公共字段.
命名的访问者属性将名称与一个或两个访问者函数相关联.访问器函数用于存储或检索与属性关联的值.这意味着您将访问限制在get或/和set accessor属性后面的某个值.
比较两者,第一个选项不会对您的值的访问方式进行封装或控制.第二个允许您指定您的值是否可以读取"get accessor",写入"set accessor"或两者.
UPDATE
关于你的次要疑问(在评论中)这里有一个关于我刚刚烹饪的Ecma Script基础知识的一点点快速;):
// 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);
}
Run Code Online (Sandbox Code Playgroud)
用我的jsfiddle来玩!
快乐的编码!
| 归档时间: |
|
| 查看次数: |
2392 次 |
| 最近记录: |