- 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
广告