扩展HTMLTextAreaElement的HTML5 ES6自定义元素会导致非法构造函数崩溃

mti*_*ani 2 javascript html5 typescript ecmascript-6 custom-element

我需要从HTMLTextAreaElement扩展自定义元素,以便在表单中使用并直接获取值.但我总是得到Illegal Constructor Message

HTML:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div>
      <working-element></working-element>
    </div>
    <div>
      <crashing-element></crashing-element>
    </div>
  </body>
  <script src="myScript.js">
</html>
Run Code Online (Sandbox Code Playgroud)

Typescript(编译为ES6到myScript.js):

// all works fine
class newElementWorks extends HTMLElement {
  constructor(){
    super();
    console.log('newElementWorks');
  }
}
customElements.define('working-element', newElementWorks);

// this one crashes on super() call
class newElementCrash extends HTMLTextAreaElement {
  constructor(){
    super();
    console.log('newElementCrash');
  }
}
customElements.define('crashing-element', newElementCrash);
Run Code Online (Sandbox Code Playgroud)

该脚本在支持ES6和Custom-Element的Chrome版本63.0.3239.132上执行

我媒体链接试图包括webcomponents /定制元素填充工具

你有什么想法为什么从HTMLElement崩溃以外的地方延伸?

小智 5

您看到的错误意味着您正在调用的对象new没有[[construct]]内部方法.

虽然规格表明您可以extendHTML*元素类它似乎并没有在这个时候(见一个类似的问题:支持https://github.com/webcomponents/custom-elements/issues/6),所以你只能扩展HTMLElement此刻.

  • 感谢您的快速响应。我想知道为什么网上有这么多教程,如果它在任何浏览器中都不起作用,那么从 HTML*Element 扩展就完成了。 (2认同)