在 Web 组件中,要注册一个元素,您只需键入:
var XFoo = document.registerElement('x-foo', {
prototype: Object.create(HTMLElement.prototype)
});
要创建元素,您可以执行以下操作之一:
<x-foo></x-foo>
var xFoo = new XFoo();
document.body.appendChild(xFoo);
var xFoo = document.createElement( 'x-foo')
document.body.appendChild(xFoo);
这一切都很好,花花公子。当您谈论扩展现有元素时,问题就开始了。
var XFooButton = document.registerElement('x-foo-button', {
prototype: Object.create(HTMLButtonElement.prototype),
extends: 'button'
});
问题1:为什么重复?在这里,'button'
应该足够了(特别是因为它很容易计算出元素的原型Object.getPrototypeOf(document.createElement(tag));
问题 2:这些信息在内部是如何使用的?例如,如果您有prototype: Object.create(HTMLFormElement.prototype
并且extends: 'button'
(之后的内容extends
与传递的原型不匹配)会发生什么
要创建一个,您可以执行以下操作之一:
<button is="x-foo-button"></button>
var xFooButton = new XFooButton();
document.body.appendChild(xFoo);
var xFooButton = document.createElement('button', 'x-foo-button');
document.body.appendChild(xFooButton);
问题3:既然x-foo-button
extends很明显button
,为什么我们在使用的时候还要同时指定document.createElement()
呢?我怀疑这是因为document.createElement()
简单地创建了一个带有 syntax 的标签<button is="x-foo-button"></button>
,这让我想到了下一个问题:
问题 4:is
语法的意义何在?这样做的实际区别是什么:
var XFooButton = document.registerElement('x-foo-button', {
prototype: Object.create(HTMLButtonElement.prototype),
extends: 'button'
});
和这个:
var XFooButton = document.registerElement('x-foo-button', {
prototype: Object.create(HTMLButtonElement.prototype),
});
除了 1)第一种语法需要<button is="x-foo-button"></button>
在文档中创建一个实例 2)第二种语法可以用于任何元素,而不仅仅是自定义元素的扩展?