gpt4 book ai didi

javascript - 保护 "private"类成员免遭修改

转载 作者:行者123 更新时间:2023-12-02 22:57:28 26 4
gpt4 key购买 nike

我使用 getter 仅查看我的私有(private)属性(property),但是当我使用 get 时,我也可以更改我的对象。我该怎么办??

function Circle(radius = 1) {

let number = radius;
this.draw = ()=> number;

let defaultLocation = {x: 0 , y: 0};

Object.defineProperty(this,"defaultLocation",{
get(){ return defaultLocation},

// set(value) {
// if (!value.x || !value.y)
// throw new Error('invalid location.');
// defaultLocation = value;
// }
})
}
const another = new Circle(2);
another.defaultLocation.x = 100 ;
console.log(another);
console.log(another.defaultLocation);

最佳答案

您将返回一个对象 defaultLocation,它有 2 个属性:xy。默认对象是可变的。使用 getter 返回对象不会使对象变得不可变。

您必须创建一个具有“不可变”属性的对象并返回该对象。

let defaultLocation = {};
Object.defineProperty(defaultLocation,"x", {
value: 0,
});
Object.defineProperty(defaultLocation,"y", {
value: 0,
});

Object.defineProperty(this,"defaultLocation",{
get(){ return defaultLocation}
});

这样,您就无法使用 defaultLocation.x = 100; 等赋值来更改 defaultLocation.xdefaultLocation.y 值。这样,defaultLocation.x 仍将返回 0

如果要修改属性,可以通过再次调用 defaultLocation 上的 Object.defineProperty 或使用另一个变量并修改该变量来实现:

// Method 1 (more verbose and less performant)
Object.defineProperty(defaultLocation,"x", {
configurable: true,
value: 0,
});
console.log(defaultLocation.x);
Object.defineProperty(defaultLocation,"x", {
configurable: true,
value: 10,
});
console.log(defaultLocation.x);

// Method 2
let _x = 0;
Object.defineProperty(defaultLocation,"x", {
get: () => _x,
});
console.log(defaultLocation.x);
_x = 10;
console.log(defaultLocation.x);

关于javascript - 保护 "private"类成员免遭修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57927114/

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