一个突发奇想,如果要拦截class的属性【未经授权禁止转载】【访问 www.tangshuang.net 获取更多精彩内容】变化,除了用defineProperty【本文受版权保护】【原创内容,转载请注明出处】进行重写,难道不能用Proxy吗?于是,著作权归作者所有,禁止商业用途转载。未经授权,禁止复制转载。产生了下面这段代码。
【原创不易,请尊重版权】【转载请注明来源】【版权所有,侵权必究】class A {
name = 'aaa'
age = 0
constructor() {
return new Proxy(this, {
get: (_, key) => this[key],
set: (_, key, value) => {
console.log(key, value)
this[key] = value
return true
},
})
}
say() {
console.log(this.name, this.age)
}
update(key, value) {
this[key] = value
}
}
在构造函数中return new Pro【作者:唐霜】本文版权归作者所有,未经授权不得转载。xy(this)真是够风骚的操作。
【本文首发于唐霜的博客】【本文受版权保护】本文版权归作者所有,未经授权不得转载。本文版权归作者所有,未经授权不得转载。

一般吾辈会用 class static function 或者注解来解决