![](/img/trans.png)
[英]Object.defineProperty not recognising getter or setter syntax
[英]Can Object.defineProperty only modify the setter?
我希望對象具有一個字段,該字段在讀取時返回字段值,並且當將val寫入字段時,我想在寫入之前修改val。 我當前的代碼是這樣的:
function Cat(lives) {
var self = this;
var privateLives;
Object.defineProperty(self, 'publicLives', {
get: function() {return privateLives;},
set: function(val) {privateLives = 7 * val;}
});
}
有沒有不做私有變量的方法嗎? 理想情況下,我只是將設置器設為:
function(val) {self.publicLives = 7 * val;}
但這會在安裝程序調用自身時導致溢出。 有什么方法可以使它不會循環設置器(因此,只有在設置器作用域之外的賦值會調用設置器,而在設置器中的賦值只是正常賦值)? 如果可能的話,當setter寫入公共字段時,我也不需要顯式定義getter。
在ES6中,一種替代方法是將Proxy對象與[[Set]]陷阱一起使用 :
function Cat(lives) {
return new Proxy(this, {
set: function(target, prop, val) {
target[prop] = val;
if (prop === 'publicLives') target[prop] *= 7;
return true;
}
});
}
不,這是不可能的-屬性只能是數據屬性或訪問器屬性,不能同時是兩者。 當然,您不一定需要將值存儲在setter的私有變量中,也可以使用其他屬性或其他對象上的屬性(例如@Oriol的代理)。 如果要避免使用私有變量,則“私有”屬性是標准方法:
function Cat(lives) {
this.publicLives = lives;
}
Object.defineProperty(Cat.prototype, 'publicLives', {
get: function() {return this._privateLives;},
set: function(val) { this._privateLives = 7 * val;}
});
但是,您也可以做一些棘手的事情,並使用不斷重復定義的常量getter函數來隱藏“私有變量”:
Object.defineProperty(Cat.prototype, 'publicLives', {
set: function setter(val) {
val *= 7;
Object.defineProperty(this, 'publicLives', {
get: function() { return val; }
set: setter,
configurable: true
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.