【发布时间】:2019-02-06 12:41:05
【问题描述】:
我正在创建一个 @Component 装饰器,它会在类的构造函数中进行调解,以便在构造后执行一些工作。从下面的代码可以看出,工作是在init方法中实现的。
export function Component (Cls) {
function Class (...args) {
let self = new Cls (...args); // (1)
init (self, ...args);
return self;
}
Class.prototype = Cls.prototype;
return Class;
}
当我在常规课程上测试此代码时,一切正常。这是一个工作示例:
class Base { ... }
@Component
class Core extends Base {
constructor () {
super (); // init is invoked
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
尽管如此,当我尝试装饰 Web 组件时,会获得 TypeError: Illegal constructor 消息。
@Component
class Core extends HTMLElement {
constructor () {
super ();
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
customElements.define ('x-core', Core);
let coreX = document.createElement ('x-core');
document.body.appendChild (coreX);
我意识到问题是HTMLElement 不支持通过 new 运算符直接构造 - 请参阅第一个列表中的 (1) - 但我需要一个过程来装饰任何类的构造函数,即使它们是自定义元素。
有什么想法?
工作设置:Chrome 68·Babel 7.0.0-beta.51 和 babel-plugin-transform-decorators-legacy
【问题讨论】:
-
如果您根本不能使用
new,您将如何使用Core?Component在这里并不重要,恕我直言。 -
非常感谢@appleapple 我已经完成了后者的sn-p。在我的第一次修订中,我没有包含最后 3 行,因此存在相同的问题,但没有触发错误。