[英]What's the reason for Illegal Invocation in this extended DocumentFragment?
I tried to extend DocumentFragment
object. 我试图扩展
DocumentFragment
对象。
function DocFragment() {
this.addHTML = function(html) {
var div = document.createElement("div");
div.innerHTML = html;
while(div.firstChild) this.appendChild(div.firstChild);
};
}
DocFragment.prototype = document.createDocumentFragment();
var doc = new DocFragment();
doc.addHTML("<b>after</b><i>list</i>");
However I got Illegal Invocation
error on this.appendChild
line. 但是我在
this.appendChild
行上this.appendChild
了Illegal Invocation
错误。 I know it is a bad idea to extend host objects, I'm just curious why this error appeared? 我知道扩展主机对象是一个坏主意,我只是好奇为什么会出现这个错误? Is there any other appropriate way to add some methods to DocumentFragment beside passing it to some function like
function addHTML(doc, html)
? 有没有其他适当的方法向DocumentFragment添加一些方法,除了将它传递给
function addHTML(doc, html)
类的function addHTML(doc, html)
?
This is more or less the difference between document.createDocumentFragment()
and new DocumentFragment()
. 这或多或少是
document.createDocumentFragment()
和new DocumentFragment()
之间的区别。 document.createDocumentFragment()
does some opaque initialization that you can't copy. document.createDocumentFragment()
执行一些无法复制的不透明初始化。
Is there any other appropriate way to add some methods to
DocumentFragment
beside passing it to some function likefunction addHTML(doc, html)
?有没有其他适当的方法向
DocumentFragment
添加一些方法,除了将它传递给function addHTML(doc, html)
类的function addHTML(doc, html)
?
To take that literally, you can extend its prototype just fine: 从字面上看,你可以扩展它的原型:
DocumentFragment.prototype.addHTML = function (html) {
// …
};
You can also take the “jQuery approach” (a wrapper): 您还可以采用“jQuery方法”(包装器):
function DocFragment() {
this.fragment = document.createDocumentFragment();
}
DocFragment.prototype.addHTML = function (html) {
// Use this.fragment
};
// Copy properties and methods as necessary
Defining addHTML(doc, html)
is much cleaner than both of these, though. 但是,定义
addHTML(doc, html)
要比这两者更清晰。
You could try directly extending the prototype for DocumentFragment. 您可以尝试直接扩展DocumentFragment的原型。
DocumentFragment.prototype.addHTML = function(html) {
var div = document.createElement("div");
div.innerHTML = html;
while(div.firstChild) this.appendChild(div.firstChild);
};
Or if you are squeamish about this, you could try just extending (in jQuery or Underscore or something) like so: 或者,如果你对此感到娇气,你可以尝试扩展(在jQuery或Underscore或其他东西中),如下所示:
var DocFragment = _(DocumentFragment).extend();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.