プロキシが確実に発生する場合、設定された機能を制限する1つの解決策は、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()
用ブラウザの互換性はまだ明らかにされていません。しかし、それはノードv8.1.3で私のために働きます
あなたが解決しようとしている問題についてもっと詳しく説明できますか?あなたは、(プロキシを使って)いくつかの可能な解決策を説明しているようですが、あなたが達成しようとしていることを本当に記述していません。 – jfriend00