我想确保当在类外更改对象的属性时引发错误。这是我尝试执行的操作:
class Example {
constructor(index) {
this.index = index;
Object.defineProperty(this, 'index', {
set() {
throw new AssertionError("can't set attribute");
}
});
}
}
class AssertionError extends Error {
constructor(message) {
super();
this.name = "AssertionError";
this.message = message;
}
}
let example = new Example(5);
console.log(example.index); //prints undefined instead of 5
example.index = 10; // I want to throw an AssertionError hereRun Code Online (Sandbox Code Playgroud)
就像我想要的那样抛出错误,但是索引值未定义。我仍然希望能够在类内部更改属性,但是我想防止属性在类外部更改。
您可以通过调用来重新定义属性defineProperty。您应该给它吸气剂:
Object.defineProperty(this, 'index', {
get() { return index; },
set() {
throw new AssertionError("can't set attribute");
}
});
Run Code Online (Sandbox Code Playgroud)
任何给定的属性名称只能使用一次;属性必须是普通属性或具有getter / setter函数的属性。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |