使用装饰器包装类的过程会导致超类无法访问该类的属性.为什么?
我有一些代码:
这是代码:
function wrap(target: any) {
// the new constructor
var f: any = function (...args) {
return new target();
}
f.prototype = target.prototype;
return f;
}
@wrap
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var a = new Extended()
console.log(new Extended().prop) // I'm expecting 5 here, but I get undefined.
Run Code Online (Sandbox Code Playgroud)
我确信这是一般原型的一些细微差别,或者是TypeScript处理它们的具体方式,我没有掌握.
TSV*_*TSV 15
此代码的工作对我来说:
function logClass(target: any) {
// save a reference to the original constructor
var original = target;
// the new constructor behaviour
var f : any = function (...args) {
console.log("New: " + original.name);
return original.apply(this, args)
}
// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
}
@logClass
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var b = new Base()
console.log(b.prop)
var a = new Extended()
console.log(a.prop)
Run Code Online (Sandbox Code Playgroud)
uri*_*ish 10
使用 ES2015 Proxy 覆盖构造函数的解决方案:
function wrap(target: any) {
return new Proxy(target, {
construct(clz, args) {
console.log(`Constructing ${target.name}`);
return Reflect.construct(clz, args);
}
});
}
@wrap
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var a = new Extended()
console.log(new Extended().prop);
Run Code Online (Sandbox Code Playgroud)
这是使用最新TS(3.2.4)的更现代的方法。下面还使用了装饰器工厂模式,因此您可以传递属性:
function DecoratorName(attr: any) {
return function _DecoratorName<T extends {new(...args: any[]): {}}>(constr: T){
return class extends constr {
constructor(...args: any[]) {
super(...args)
console.log('Did something after the original constructor!')
console.log('Here is my attribute!', attr.attrName)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处以获取更多信息:https : //www.typescriptlang.org/docs/handbook/decorators.html#class-decorators
归档时间: |
|
查看次数: |
8789 次 |
最近记录: |