简体   繁体   English

在这个扩展的DocumentFragment中非法调用的原因是什么?

[英]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.appendChildIllegal 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 like function 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.

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