2020-09-24 06:29:05 +08:00
|
|
|
export default function magicMethods(Clazz: any) {
|
2020-03-11 17:23:28 +08:00
|
|
|
const classHandler = Object.create(null)
|
|
|
|
|
2020-09-24 06:37:31 +08:00
|
|
|
classHandler.construct = (_: any, args: any) => {
|
2020-09-24 06:29:05 +08:00
|
|
|
const instance = new Clazz(...args)
|
2020-03-11 17:23:28 +08:00
|
|
|
const instanceHandler = Object.create(null)
|
2020-09-24 06:29:05 +08:00
|
|
|
const get = Object.getOwnPropertyDescriptor(Clazz.prototype, '__get')
|
2020-03-11 17:23:28 +08:00
|
|
|
|
|
|
|
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]
|
|
|
|
}
|
2020-09-24 06:29:05 +08:00
|
|
|
|
|
|
|
return get.value.call(target, name)
|
2020-03-11 17:23:28 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
instance.proxy = new Proxy(instance, instanceHandler)
|
2020-08-22 05:43:08 +08:00
|
|
|
instance.emit('createdProxy')
|
2020-03-11 17:23:28 +08:00
|
|
|
|
|
|
|
return instance.proxy
|
|
|
|
}
|
|
|
|
|
2020-09-24 06:29:05 +08:00
|
|
|
return new Proxy(Clazz, classHandler)
|
|
|
|
}
|