如果代理肯定會發生,那麼限制設置功能的一種可能的解決方案是返回一個ES6代理實例。
默認情況下,javascript中的構造函數會自動返回this
對象,但您可以通過實例化this
上的代理作爲目標來定義並返回自定義行爲。請記住,代理中的set方法應該返回一個布爾值。
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, schema) {
// 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 name(email) {
this._email = email.trim();
}
}
所以,現在你不能根據代理設置非可置性。
let row = new Row({
name : 'John Doe',
email : '[email protected]'
}, Schema);
row.password = 'blahblahblah'; // Error: Cannot set the password property
也可以在get方法上具有自定義行爲。
注:根據MDN的那一刻,對handler.set()
瀏覽器的兼容性不是很明顯呢。然而它適用於Node v8.1.3
你能描述一下你想解決的問題嗎?您似乎正在描述一些可能的解決方案(使用代理),但並未真正描述您要完成的任務。 – jfriend00