福禄丸丶 2020-05-28 12:33 采纳率: 66.7%
浏览 784
已采纳

使用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.

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

  • 写回答

1条回答 默认 最新

  • 阿阿阿阿嚏! 2020-05-28 18:31
    关注

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

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

    望采纳

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)