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

标签 javascript oop object

我使用 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/

相关文章:

c# - 基本成员初始化部分 C#?

javascript - 添加新行后重新排序 slickgrid?

javascript - 重新执行 JavaScript 文件

javascript - 无法理解这个例子是如何工作的。 lastIndexOf() 方法

javascript - 使用 Sequelize 按连接表计数列排序

php - 如何从 php 中的静态函数内部为公共(public)变量赋值?

java - 将方法作为参数传递给另一个方法

php - 根据里氏替换原则,子类是否允许拥有公共(public)方法?

java - 当一个类被另外两个类扩展时获取空值

JavaScript 常量