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

提前创建未挂载的Web组件为何无法调用类方法?

自定义元素定义前后的构造函数差异

如果自定义元素在定义前就被创建,它会使用HTMLElement构造函数,且即便后续完成定义,这个已创建的元素仍会保留这一特性。只有再次创建该元素时,才会使用正确的自定义构造函数,具体示例如下:

const comp = document.createElement("my-comp");

console.log('定义前的第一个元素: ', comp.constructor.name);

customElements.define("my-comp", class MyComp extends HTMLElement {
    constructor() { super(); }
    myMethod() { return; }
  }
);

console.log('定义后的第一个元素: ', comp.constructor.name);

try { comp.myMethod() }
catch (e) { console.error(e) }

const secondComp = document.createElement("my-comp");
console.log('第二个元素: ', secondComp.constructor.name);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:05:11