If the proxy is certain to happen for you, one possible solution to limit the set functionality is returning an ES6 Proxy instance.
By default, the constructor in javascript returns this
object automatically but you could define and return a custom behavior by instantiating a proxy on this
as a target. Keep in mind that the set method in proxy should return a boolean value.
MDN: The set method should return a boolean value. Return true to indicate
that assignment succeeded. If the set method returns false, and the
assignment happened in strict-mode code, a TypeError will be thrown.
class Row {
constructor(entry) {
// some stuff
return new Proxy(this, {
set(target, name, value) {
let setables = ['name', 'email'];
if (!setables.includes(name)) {
throw new Error(`Cannot set the ${name} property`);
} else {
target[name] = value;
return true;
}
}
});
}
get name() {
return this._name;
}
set name(name) {
this._name = name.trim();
}
get email() {
return this._email;
}
set email(email) {
this._email = email.trim();
}
}
So, now you are not allowed to set the non-setable properties according to the proxy.
let row = new Row({
name : 'John Doe',
email : 'john@doe.com'
});
row.password = 'blahblahblah'; // Error: Cannot set the password property
It's also possible to have s custom behavior on get method too.
However, beware and take care of overriding the reference that is returned to the calling context.
Note: The sample code has been tested on Node v8.1.3 and modern browsers.