2020-03-28 06:17:28 +08:00
|
|
|
export default function magicMethods(clazz: any) {
|
2020-03-11 17:23:28 +08:00
|
|
|
const classHandler = Object.create(null)
|
|
|
|
|
|
|
|
classHandler.construct = (target: any, args: any) => {
|
|
|
|
const instance = new clazz(...args)
|
|
|
|
const instanceHandler = Object.create(null)
|
|
|
|
const get = Object.getOwnPropertyDescriptor(clazz.prototype, '__get')
|
|
|
|
|
|
|
|
if (get) {
|
|
|
|
instanceHandler.get = (target: any, name: any) => {
|
|
|
|
if (typeof name !== 'string') {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-03-30 19:09:08 +08:00
|
|
|
const exists = name in target
|
|
|
|
|| name.startsWith('_')
|
|
|
|
|| ['then', 'catch'].includes(name)
|
|
|
|
|
2020-03-11 17:23:28 +08:00
|
|
|
if (exists) {
|
|
|
|
return target[name]
|
|
|
|
} else {
|
|
|
|
return get.value.call(target, name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
instance.proxy = new Proxy(instance, instanceHandler)
|
2020-04-01 04:17:54 +08:00
|
|
|
instance.init()
|
2020-03-11 17:23:28 +08:00
|
|
|
|
|
|
|
return instance.proxy
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Proxy(clazz, classHandler)
|
|
|
|
}
|