- ES6 教程
- ES6 - 首頁
- ES6 - 概覽
- ES6 - 環境
- ES6 - 語法
- ES6 - 變數
- ES6 - 運算子
- ES6 - 決策
- ES6 - 迴圈
- ES6 - 函式
- ES6 - 事件
- ES6 - cookie
- ES6 - 頁面重定向
- ES6 - 對話方塊
- ES6 - void 關鍵字
- ES6 - 頁面列印
- ES6 - 物件
- ES6 - 數字
- ES6 - 布林值
- ES6 - 字串
- ES6 - 符號
- ES6 - 新的字串方法
- ES6 - 陣列
- ES6 - 日期
- ES6 - 數學
- ES6 - RegExp
- ES6 - HTML DOM
- ES6 - 迭代器
- ES6 - 集合
- ES6 - 類
- ES6 - Map 和 Set
- ES6 - Promise
- ES6 - 模組
- ES6 - 錯誤處理
- ES6 - 物件擴充套件
- ES6 - Reflect API
- ES6 - Proxy API
- ES6 - 驗證
- ES6 - 動畫
- ES6 - 多媒體
- ES6 - 除錯
- ES6 - 影像對映
- ES6 - 瀏覽器
- ES7 - 新特性
- ES8 - 新特性
- ES9 - 新特性
- ES6 實用資源
- ES6 - 快速指南
- ES6 - 實用資源
- ES6 - 討論
ES6 - handler.set()
以下是使用建構函式和自定義 getter 方法(fullName)定義類 Student 的示例。建構函式使用 firstName 和 lastName 作為引數。該程式建立了一個代理,並定義了一個在 firstName 和 lastName 上攔截所有 set 操作的 handler 物件。如果屬性值長度不超過 2,該 handler 物件將丟擲一個錯誤。
<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
廣告