简体   繁体   English

向DOM元素添加新属性与扩展DOM元素原型

[英]Adding new attributes to DOM elements vs extending DOM elements prototype

What is the difference between the two? 两者有什么区别?

Say you have 说你有

var e = document.getElementById("myelement")

I see an example of something like this: 我看到一个类似这样的例子:

e.prototype.print = function(){
 if(this.nodeType==3)
   console.log(this.nodeText);
}

vs an adding new attributes to DOM elements example: 与在DOM元素中添加新属性的示例:

e.accessed = true;

where you're adding the accessed property to element. 在其中将accessed属性添加到element。

It seems like both these examples are adding a new property/attribute to an element, just that the former adds the property to the prototype, so that all objects that inherit the prototype get the new property as well? 似乎这两个示例都向元素添加了新的属性/属性,就像前者将属性添加到原型中一样,以便所有继承原型的对象也都获得了新属性?

So if myelement was the only object inherited from it's prototype, would the following be equivalent to the first example I posted? 因此,如果myelement是唯一从其原型继承的对象,那么以下内容是否等同于我发布的第一个示例?

e.print=function(){
 if(this.nodeType==3)
   console.log(this.nodeText);
}

Try using document.registerElement . 尝试使用document.registerElement See Custom Elements , Introduction to Custom Elements 请参阅“ 自定义元素”“自 定义元素 简介”

 var proto = Object.create(HTMLDivElement.prototype); proto.print = function() { console.log(this.nodeName, this.textContent); return this } document.registerElement("x-component", { extends: "div", prototype: proto }); var divs = document.getElementsByTagName("div"); for (var i = 0; i < divs.length; i++) { if ("print" in divs[i]) { console.log(divs[i].print()) } } document.registerElement("x-foo", { prototype: Object.create(HTMLParagraphElement.prototype, { print: { get: function() { console.log(this.nodeName, this.textContent) return this; }, enumerable: true, configurable: true } //, // specify more members for your prototype. }), extends: "p" }); var foo = document.createElement("p", "x-foo"); foo.innerHTML = 123; document.body.appendChild(foo); console.log(foo.print); 
 <div is="x-component">abc</div> <div>def</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM