如何在 TypeScript 中使用装饰器正确包装构造函数 [英] How to properly wrap constructors with decorators in TypeScript

查看:38
本文介绍了如何在 TypeScript 中使用装饰器正确包装构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用装饰器包装类的过程会导致超类无法访问该类的属性.为什么?

The process of wrapping a class with a decorator causes superclasses to be unable to access that classes' properties. Why?

我有一些代码:

  1. 创建一个装饰器,用一个新的构造函数替换一个类的构造函数,该构造函数应该做同样的事情.
  2. 使用属性创建基类.
  3. 使用包装装饰器包装基类.
  4. 创建一个扩展基类的类.
  5. 尝试访问扩展类的属性.这是失败的部分.

代码如下:

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.

我确信这是一般原型或 TypeScript 处理它们的特定方式的一些细微差别,我不了解.

I'm sure this is some nuance of either prototypes in general or the specific way that TypeScript handles them that I do not grasp.

推荐答案

此代码 对我有用:

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);
    return new original(...args); // according the comments
  }

  // 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)

这篇关于如何在 TypeScript 中使用装饰器正确包装构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆