所有参数未定义但属性有值
All params undefined but attributes has values
在使用 custom elements 时,我注意到 attachedCallback
函数有一个已填充的 attributes
集合。即它是一个 NamedNodeMap
包含所有传递给元素的属性。
我还注意到在 attachedCallback
函数上指定参数总是会产生 undefined
.
如何在函数中设置 attributes
集合,但指定的参数是 undefined
?这纯粹是因为浏览器供应商的实现,还是在 JavaScript 中有我不知道的方法来做到这一点?
示例:
var proto = Object.create(HTMLElement.prototype);
proto.attachedCallback = function (elem) {
console.log(elem); // undefined
console.log(this.attributes); // NamedNodeMap
};
在堆栈的某处,正在调用 apply
或 call
,其中第一个参数是包含 attributes
属性 的对象。
以下是您可以在代码中执行此操作的方法:
var proto = Object.create(HTMLElement.prototype);
proto.attachedCallback = function (elem) {
console.log(elem); // undefined
console.log(this.attributes); // NamedNodeMap
};
var randomObjectWithAttributes = {
attributes: new NamedNodeMap()
};
proto.attachedCallback.call(randomObjectWithAttributes);
这是 Javascript 的优点之一,您可以使用 call
和 apply
将函数视为属于对象的原型,即使它们不属于t.
在使用 custom elements 时,我注意到 attachedCallback
函数有一个已填充的 attributes
集合。即它是一个 NamedNodeMap
包含所有传递给元素的属性。
我还注意到在 attachedCallback
函数上指定参数总是会产生 undefined
.
如何在函数中设置 attributes
集合,但指定的参数是 undefined
?这纯粹是因为浏览器供应商的实现,还是在 JavaScript 中有我不知道的方法来做到这一点?
示例:
var proto = Object.create(HTMLElement.prototype);
proto.attachedCallback = function (elem) {
console.log(elem); // undefined
console.log(this.attributes); // NamedNodeMap
};
在堆栈的某处,正在调用 apply
或 call
,其中第一个参数是包含 attributes
属性 的对象。
以下是您可以在代码中执行此操作的方法:
var proto = Object.create(HTMLElement.prototype);
proto.attachedCallback = function (elem) {
console.log(elem); // undefined
console.log(this.attributes); // NamedNodeMap
};
var randomObjectWithAttributes = {
attributes: new NamedNodeMap()
};
proto.attachedCallback.call(randomObjectWithAttributes);
这是 Javascript 的优点之一,您可以使用 call
和 apply
将函数视为属于对象的原型,即使它们不属于t.