如何使重写类实例字段变得不可能



我想创建具有可写:false字段的class。任务是:

  • 我需要为这些值使用构造函数
  • 我们只能写一次这些值。F.e:
Class Room {
constructor(length, width) {
this.length = length; 
this.width = width; 
}
}
let room = new Room(20, 10); 
console.log(room.length) // 20
room.length = 10000 // Error ```
I have no idea how to do it. Does defineProperty method fit?

在构造函数中调用Object.defineProperty有效:

class Room {
constructor(length, width) {
Object.defineProperty(this, 'length', { value: length });
Object.defineProperty(this, 'width', { value: width });
}
}
let room = new Room(20, 10);
console.log(room.length) // 20
room.length = 10000 // Does not do anything, throws in strict mode
console.log(room.length) // 20

如果您想在尝试分配时抛出错误,请在严格模式下运行脚本,或者使用getters/ssetters:

class Room {
constructor(length, width) {
Object.defineProperty(this, 'length', { get() { return length }, set() { throw new Error() }});
Object.defineProperty(this, 'width', { get() { return width }, set(){ throw new Error() }});
}
}
let room = new Room(20, 10);
console.log(room.length) // 20
room.length = 10000 // setter throws

如果这应该是实例的所有属性的行为,并且正在寻找一个不可变的对象,那么您可以调用Object.freeze:

class Room {
constructor(length, width) {
this.length = length;
this.width = width;
Object.freeze(this);
}
}
let room = new Room(20, 10);
console.log(room.length); // 20;
room.length = 10000; // No effect. Throws error in strict mode
console.log(room.length); // 20
room.newProp = "hi"; // No effect either.
console.log("newProp" in room); // false

最新更新