Es6-handler-set
提供:Dev Guides
ES6-handler.set()
次の例では、コンストラクターとカスタムゲッターメソッドfullNameを使用してStudentクラスを定義しています。 コンストラクターはパラメーターとしてfirstNameおよびlastNameを取ります。 プログラムはプロキシを作成し、firstNameおよびlastNameに対するすべてのセット操作をインターセプトするハンドラーオブジェクトを定義します。 プロパティ値の長さが2以下の場合、ハンドラーオブジェクトはエラーをスローします。
<script>
class Student{
constructor(firstName,lastName){
this.firstName = firstName
this.lastName = lastName
}
get fullName(){
return `${this.firstName} : ${this.lastName}`
}
}
const handler = {
set: function(target,property,value){
if(value.length>2){
return Reflect.set(target,property,value);
} else {
throw 'string length should be greater than 2'
}
}
}
const s1 = new Student("Tutorials","Point")
const proxy = new Proxy(s1,handler)
console.log(proxy.fullName)
proxy.firstName="Test"
console.log(proxy.fullName)
proxy.lastName="P"
</script>
上記のコードの出力は以下のようになります-
Tutorials : Point
Test : Point
Uncaught string length should be greater than 2