用类装饰器覆盖构造函数? [英] Override constructor with an class decorator?

查看:123
本文介绍了用类装饰器覆盖构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用ES7类装饰器覆盖构造函数?

How can I override a constructor with an ES7 class decorator?

例如,我希望有类似的东西:

For example, I'd like to have something like:

@injectAttributes({ foo: 42 })
class Bar {
  constructor() {
    console.log(this.foo);
  }
}

injectAttributes decorator会在创建新实例之前将其注入:

Where the injectAttributes decorator will inject attributes into new instances before they are created:

> bar = new Bar();
42
> bar.foo
42

显而易见的解决方案 - 使用不同的构造函数:

The obvious solution – using a different constructor:

 function overrideConstructor(cls, attrs) {
   Object.assign(this, attrs);
   cls.call(this);
 }

不起作用,因为创建的对象将是新构造函数的实例,不是原始类型:

Does not work because the object created will be an instance of the new constructor, not the original type:

 > bar = new overrideConstructor(Bar, {foo: 42})
 42
 > bar
 [overrideConstructor {}]
 > bar instanceof Bar
 false


推荐答案

BabelJS REPL不支持装饰器所以我使用的功能(和手动包装),但概念是相同的。

The BabelJS REPL doesn't support decorators so I am using the function (and manually wrapping) but the concept is the same.

这里是代码正常工作,以及下面的复制/粘贴:

Here is the code working, and the copy/paste below:

function injectAttributes(cls, attrs) {
  const injected = function(...args) {
    Object.assign(this, attrs);
    return cls.apply(this, args);
  }
  injected.prototype = cls.prototype;
  return injected;
}


class BareBar {
  constructor() {
    console.log(this.foo);
  }
}
const Bar = injectAttributes(BareBar, { foo: 5 })

const thing = new Bar();
console.log(thing instanceof Bar);

这打印:

5
true

装饰器创建一个新的构造函数,其中属性注入,然后复制原始原型,以便 instanceof 工作。

The decorator creates a new constructor, where attributes are injected, and then copies over the original prototype so that instanceof works.

这篇关于用类装饰器覆盖构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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