创建自定义 html 元素时未调用连接的回调

Connected callback is not being called while creating custom html elements

我正在尝试使用 JavaScript 在 HTML 中创建自定义标签。我想使用 ES6 JavaScript 语法创建自定义元素。我编写了这段代码来创建自定义元素:

customElements.define('neo-element', NeoElement);
function NeoElement (){
    var ref =  Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
<neo-element></neo-element>

我已验证 NeoElement 正确地扩展了 HTMLElement,但仍然没有在 <neo-element> 标签内打印任何内容。

任何人都可以查看代码并告诉我我在 ES5 语法中缺少什么吗?

它不起作用,因为您正在调用 customElements.define——从而将您的 <neo-element> 升级为 NeoElement 的一个实例——在您定义 NeoElement.prototypeNeoElement.prototype.constructor 之前, 和 NeoElement.prototype.connectedCallback.

如果您将 customElements.define 移动到末尾,它可以正常工作:

function NeoElement() {
    var ref = Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
customElements.define('neo-element', NeoElement);
<neo-element></neo-element>