使用TypeScript创建自定义元素时,编译通过,运行后却告诉我不能创建此元素,请使用new关键字,这是为什么?

使用TypeScript创建自定义元素时,编译通过,运行后却告诉我不能创建此元素,请使用new关键字,这是为什么?

问题描述:

我使用TypeScript创建了一个元素,继承自HTMLElement,如下:

class MyPanel extends HTMLElement {
    static get observedAttributes() {
        return ['width', 'height']
    }
        public Width:number;
        public Height:number;
    constructor() {
        super();// 这里运行时报错
                this.Width=Number(this.width);
                this.Height=Number(this.height);
        }

        get width() {
        return this.getAttribute('width') || 300
    }
    get height() {
        return this.getAttribute('height') || 150
    }
}
//并在末尾使用自执行函数注册了该元素
customElements.define('mcharts-mpanel', MyPanel); 

在Html中使用标签:

<mcharts-mpanel id="onePanel"></mcharts-mpanel>

编译通过,运行时在创建元素时报错,
TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

请问这是什么原因造成的?请务必告知我如何解决。谢谢!

这可能是因为HTMLElement 是一个托管对象,在扩展时就有可能出现问题。
使用es6而非es5构件和编译就行
应该可以通过修改json中的构建目标至es6解决
(代码只是例子,只修改其中的target即可)

  "compilerOptions": {
    "baseUrl": "../",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "lib": [
      "es2017",
      "dom"
    ]}

望采纳