JavaScript中Get和Set访问器的实现

 我们常用的实现方法可能是这样的:

function Field(val){
var value = val;

this.getValue =function(){
return value;
};

this.setValue =function(val){
value
= val;
};
}
var field =new Field("test");
field.setValue(
"test2")
field.getValue()
// return "test2"

标准的Get和Set访问器的实现:

function Field(val){
this.value = val;
}
Field.prototype
= {
get value(){
returnthis._value;
},
set value(val){
this._value = val;
}
};
var field =new Field("test");
field.value
="test2";
//field.value will now return "test2"

在DOM元素上Get和Set访问器的实现

HTMLElement.prototype.__defineGetter__("description", function () {
returnthis.desc;
});
HTMLElement.prototype.__defineSetter__(
"description", function (val) {
this.desc = val;
});
document.body.description
="Beautiful body";
// document.body.description will now return "Beautiful body";

通过Object.defineProperty实现访问器

Object.defineProperty(obj, prop, descriptor)

参数:

obj:目标对象

prop:需要定义的属性或方法的名字。

descriptor:目标属性所拥有的特性。

可供定义的特性列表:

  • value:属性的值
  • writable:如果为false,属性的值就不能被重写。
  • get: 一旦目标属性被访问就会调回此方法,并将此方法的运算结果返回用户。
  • set:一旦目标属性被赋值,就会调回此方法。
  • configurable:如果为false,则任何尝试删除目标属性或修改属性以下特性(writable, configurable, enumerable)的行为将被无效化。
  • enumerable:是否能在for...in循环中遍历出来或在Object.keys中列举出来。
var lost = {
loc :
"Island"
};
Object.defineProperty(lost,
"location", {
get :
function () {
returnthis.loc;
},
set :
function (val) {
this.loc = val;
}
});
lost.location
="Another island";
// lost.location will now return "Another island"
原文地址:https://www.cnblogs.com/zhepama/p/3505361.html