提前创建未挂载的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
相关产品推荐
相关产品推荐

