简体   繁体   中英

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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