You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建继承HTMLElement的类?html-element模块使用问题

正确实现方式

你不需要实例化HTML.HTMLElement,因为类继承的目标是类本身,而非类的实例。直接将HTML.HTMLElement作为父类即可:

let HTML = require('html-element');

class MyElement extends HTML.HTMLElement {
  #xValue = 0;
  constructor() {
    super();
    this.onclick = this.#clicked.bind(this);
  }

  #clicked() {
    // 编写点击事件逻辑
    this.#xValue++;
    console.log('点击次数:', this.#xValue);
  }
}

补充说明

  • html-element模块导出的HTMLElement是构造函数(类),可直接用作继承的父类,无需用new创建实例。
  • 若需注册自定义元素(模拟浏览器自定义元素API),可使用模块提供的define方法:
HTML.define('my-element', MyElement);

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:52:01