【发布时间】:2020-08-02 11:27:37
【问题描述】:
我正在尝试包装类构造函数并使用类装饰器注入一些逻辑。在我尝试扩展包装类之前一切正常:扩展类在原型中没有方法。
function logClass(Class) {
// save a reference to the original constructor
const _class = Class;
// proxy constructor
const proxy = function(...args) {
const obj = new _class(...args);
// ... add logic here
return obj
}
// copy prototype so intanceof operator still works
proxy.prototype = _class.prototype;
// return proxy constructor (will override original)
return proxy;
}
@logClass
class Base {
prop = 5;
test() {
console.log("test")
}
}
class Extended extends Base {
test2() {
console.log("test2")
}
}
var base = new Base()
base.test()
var ext = new Extended()
console.log(ext.prop)
ext.test()
ext.test2() // TypeError: ext.test2 is not a function
【问题讨论】:
-
你在使用打字稿吗?
-
是的,原始代码在 Typescript 中
-
为什么不显示原始ts代码,而是帮助我们重现?顺便说一句,您在哪个环境中使用这些装饰器,因为 javascript 平台尚不支持此功能,或者您正在使用诸如 babel 之类的转译器?
标签: javascript typescript class-decorator