gpt4 book ai didi

javascript - Object.defineProperty只能修改setter吗?

转载 作者:行者123 更新时间:2023-11-28 00:03:31 29 4
gpt4 key购买 nike

我希望我的对象有一个字段,当读取时返回字段值,并且当将 val 写入该字段时,我想在写入之前修改 val。我当前的代码是这样的:

function Cat(lives) {
var self = this;

var privateLives;
Object.defineProperty(self, 'publicLives', {
get: function() {return privateLives;},
set: function(val) {privateLives = 7 * val;}
});
}

有没有办法在不创建私有(private)变量的情况下做到这一点?理想情况下,我只需让 setter 是这样的:

function(val) {self.publicLives = 7 * val;}

但是当 setter 调用自身时,这会导致溢出。是否有某种方法可以使其不循环 setter (因此只有 setter 范围之外的赋值才会调用 setter ,而 setter 中的赋值只会执行正常分配)?如果可能的话,当 setter 写入公共(public)字段时,我也不需要显式定义 getter。

最佳答案

不,这是不可能的 - 属性只能是数据属性或访问器属性,不能同时是两者。当然,您不一定需要将值存储在 setter 的私有(private)变量中,您也可以使用不同的属性或不同对象上的属性(例如在 @Oriol 的代理中)。如果您想避免私有(private)变量,“私有(private)”属性是标准方法:

function Cat(lives) {
this.publicLives = lives;
}
Object.defineProperty(Cat.prototype, 'publicLives', {
get: function() {return this._privateLives;},
set: function(val) { this._privateLives = 7 * val;}
});

但是你也可以做一些棘手的事情,通过使用重复重新定义的常量 getter 函数来隐藏“私有(private)变量”:

Object.defineProperty(Cat.prototype, 'publicLives', {
set: function setter(val) {
val *= 7;
Object.defineProperty(this, 'publicLives', {
get: function() { return val; }
set: setter,
configurable: true
});
}
});

关于javascript - Object.defineProperty只能修改setter吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566400/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com