[英]What's the reason for Illegal Invocation in this extended DocumentFragment?
我試圖擴展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>");
但是我在this.appendChild
行上this.appendChild
了Illegal Invocation
錯誤。 我知道擴展主機對象是一個壞主意,我只是好奇為什么會出現這個錯誤? 有沒有其他適當的方法向DocumentFragment添加一些方法,除了將它傳遞給function addHTML(doc, html)
類的function addHTML(doc, html)
?
這或多或少是document.createDocumentFragment()
和new DocumentFragment()
之間的區別。 document.createDocumentFragment()
執行一些無法復制的不透明初始化。
有沒有其他適當的方法向
DocumentFragment
添加一些方法,除了將它傳遞給function addHTML(doc, html)
類的function addHTML(doc, html)
?
從字面上看,你可以擴展它的原型:
DocumentFragment.prototype.addHTML = function (html) {
// …
};
您還可以采用“jQuery方法”(包裝器):
function DocFragment() {
this.fragment = document.createDocumentFragment();
}
DocFragment.prototype.addHTML = function (html) {
// Use this.fragment
};
// Copy properties and methods as necessary
但是,定義addHTML(doc, html)
要比這兩者更清晰。
您可以嘗試直接擴展DocumentFragment的原型。
DocumentFragment.prototype.addHTML = function(html) {
var div = document.createElement("div");
div.innerHTML = html;
while(div.firstChild) this.appendChild(div.firstChild);
};
或者,如果你對此感到嬌氣,你可以嘗試擴展(在jQuery或Underscore或其他東西中),如下所示:
var DocFragment = _(DocumentFragment).extend();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.