简体   繁体   English

如何在属性更改时抛出错误?

[英]How to throw an error when an attribute is changed?

I want to make sure an error gets thrown when an attribute of an object gets changed outside the class. 我想确保在对象的属性在类外部更改时抛出错误。 Here's how I tried to do it: 这是我试图这样做的方式:

 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 here 

The error gets thrown just like I wanted, but the index value is undefined. 错误会像我想要的那样被抛出,但索引值是未定义的。 I still want to be able to change the attribute inside of the class, but I want to prevent the attribute from changing outside of the class. 我仍然希望能够更改类内部的属性,但我想阻止该属性在类外部进行更改。

You redefine the property with the call to defineProperty . 您通过调用defineProperty重新定义属性。 You should give it a getter: 你应该给它一个吸气剂:

Object.defineProperty(this, 'index', {
  get() { return index; },
  set() {
    throw new AssertionError("can't set attribute");
  }
});

Any given property name can only be used once; 任何给定的属性名称只能使用一次; a property has to either be a plain property or a property with getter/setter functions. 属性必须是普通属性或具有getter / setter函数的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM