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.
To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function's declaration after its parameters. A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow ( -> ).
throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.
throw new Error("My error"): this returns you an object where you can access the error value from the message property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With