首页 > 解决方案 > How to make impossible rewriting Class instances fields

问题描述

I want to create Class with writable:false-fields. The task is:

 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?

标签: javascriptecmascript-6

解决方案


Calling Object.defineProperty in the constructor works:

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

If you want to throw an error when the assignment is attempted, either run the script in strict mode, or use getters/setters instead:

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


推荐阅读