我需要在对象的原型上创建getter
和setter
属性(ES5)。目前我正在使用以下代码,它可以工作,但我想知道:
Object.defineProperties()
吗?我的目标是ES5,仅限vanilla JS,浏览器环境。
实施例: https://jsfiddle.net/0yLotg35/
function Color() {}
Color.prototype = {
_name: '',
get name() {
return this._name;
},
set name(value) {
this._name = value;
},
_readOnly: true,
get readOnly() {
return this._readOnly;
}
};
var myColor = new Color();
myColor.name = 'red';
alert(myColor.name);
alert(myColor.readOnly);
myColor.readOnly = false;
alert(myColor.readOnly); // value it is not changed
答案 0 :(得分:1)
是的,如果您需要动态添加属性,可以使用defineProperty
为什么需要替代方案?在不知道用例的情况下很难提出建议
var obj = {};
Object.defineProperties(obj, {
"property1": {
value: true,
writable: true
},
"property2": {
value: "Hello",
writable: false
}
});
function Archiver() {
var temperature = null;
var archive = [];
Object.defineProperty(this, 'temperature', {
get: function() {
console.log('get!');
return temperature;
},
set: function(value) {
temperature = value;
archive.push({ val: temperature });
}
});
this.getArchive = function() { return archive; };
}
var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
function Archiver() {
// Can't define the array on the prototype or it would be shared by instances
this._archive = [];
}
Archiver.prototype = {
_temperature: null,
getArchive: function() {
return this._archive;
}
}
Object.defineProperty(Archiver.prototype, 'temperature', {
get: function() {
return this._temperature;
},
set: function(value) {
this._temperature = value;
this._archive.push({ val: value });
}
});
var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
console.log(arc.getArchive()); // [{ val: 11 }, { val: 13 }]
var arc2 = new Archiver();
arc2.temperature; // 'get!'
arc2.temperature = 10;
arc2.temperature = 15;
console.log(arc2.getArchive()); // [{ val: 10 }, { val: 15 }]