目前我使用下面的代碼來定義getter和setter方法我的課:object.defineProperty環路
Object.defineProperty(FPProject.prototype, 'name', {
get: function() { return this.get('name'); },
set: function(aValue) {return this.set('name', aValue);}
});
Object.defineProperty(FPProject.prototype, 'code', {
get: function() { return this.get('code'); },
set: function(aValue) {return this.set('code', aValue);}
});
Object.defineProperty(FPProject.prototype, 'clientName', {
get: function() { return this.get('clientName'); },
set: function(aValue) {return this.set('clientName', aValue);}
});
Object.defineProperty(FPProject.prototype, 'client', {
get: function() { return this.get('client'); },
set: function(aValue) {return this.set('client', aValue);}
})
我認爲我可以優化這段代碼是這樣的:
var fields = ['name','code','clientName','client'];
for (var i = 0; i < fields.length; i ++) {
Object.defineProperty(FPProject.prototype, fields[i], {
get: function() { return this.get(fields[i]); },
set: function(aValue) {return this.set(fields[i], aValue);}
});
}
但它不工作!我沒有控制檯錯誤,只是不能設置屬性...?
+1我一直忘記這個優秀的選擇。 –