javascript - How to make impossible rewriting Class instances fields
问题描述
I want to create Class with writable:false-fields. The task is:
- I need to use constructor for these values;
- We can write these values only once. 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?
解决方案
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
推荐阅读
- intellij-idea - 有没有办法在intellij 15中断点整个项目
- java - MPAndroidChart 自定义水平条形图
- android - 将适配器与不同的布局管理器合并
- python - 有没有办法将屏幕上的所有文本放入 python3 中的数组中
- java - 在共享对象文件中查找 Android Java 可用方法
- c# - Unity 想要从另一个数组中获取游戏对象
- c - 为什么 Helgrind 显示“违反锁定顺序”错误消息?
- java - 不接受文件中的更改
- c# - 检查逗号分隔字符串中的 id 是否与另一个字符串数组中的任何 id 匹配
- flutter - Flutter - 单个项目中 Web 和 Android 的不同点击操作