2014-07-24 1 views
1

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 줄에 Illegal Invocation 오류가 발생했습니다. 호스트 객체를 확장하는 것이 좋지 않다는 것을 알고 있습니다. 왜이 오류가 나타나는 지 궁금합니다. function addHTML(doc, html) 같은 일부 함수에 전달하는 것 외에도 DocumentFragment에 몇 가지 메서드를 추가하는 다른 적절한 방법이 있습니까?

답변

2

document.createDocumentFragment()new DocumentFragment() 사이의 차이는 다소 차이가 있습니다. document.createDocumentFragment() 복사 할 수없는 불투명 초기화가 수행됩니다.

function addHTML(doc, html) 같은 일부 기능에 전달 옆에 DocumentFragment에 몇 가지 방법을 추가 할 수있는 다른 적절한 방법이 있나요?

function DocFragment() { 
    this.fragment = document.createDocumentFragment(); 
} 

DocFragment.prototype.addHTML = function (html) { 
    // Use this.fragment 
}; 

// Copy properties and methods as necessary 

addHTML(doc, html)을 정의하는 것은 (래퍼)

DocumentFragment.prototype.addHTML = function (html) { 
    // … 
}; 

당신은 또한 "jQuery를 접근 방식"을 수행 할 수 있습니다

당신은 잘 프로토 타입을 확장 할 수 있습니다, 문자 그대로를 촬영하려면 이 두 가지보다 훨씬 더 깨끗합니다.

+0

:

DocumentFragment.prototype.addHTML = function(html) { var div = document.createElement("div"); div.innerHTML = html; while(div.firstChild) this.appendChild(div.firstChild); }; 

또는 당신은 이것에 대해 충격을받는 경우에, 당신은과 같이 (jQuery를 또는 밑줄 또는 무언가에) 확장 시도 할 수 있습니다. com/whats-wrong-with-extend-the-dom /) DOM 프로토 타입 객체의 노출이 보장되지 않기 때문에'DocumentFragment.prototype.addHTML'을 코딩하는 것은 좋지 않습니다 (IE9를 포함한 대부분의 브라우저는 이러한 인터페이스를 일반 객체로 구현하지만). "jQuery 접근법"에서는 모든 DocumentFragment 멤버를 노출하기가 어렵습니다. 물론, 열거 할 수있는 것들을 반복 할 수는 있지만 다시 DOM 레벨 2에서 보장 할 수는 없습니다. 유용한 답변을 주셔서 감사합니다.하지만 여전히 슬프다 ... –

1

DocumentFragment의 프로토 타입을 직접 확장 해 볼 수 있습니다. // perfectionkills : [이 링크] (HTTP에 따르면

var DocFragment = _(DocumentFragment).extend(); 
+0

좋은 제안 주셔서 감사하지만 DocumentFragment 반복 .prototype은 정의되지 않으며 DefaultValues로 인해 지정되지 않은 오류가 발생할 수도 있습니다. [this link] (http://bclary.com/2004/11/07/#a-4.3.8), 특히 호스트 객체에 관한 부분 - DOM 객체는이 별난 패밀리의 일부입니다. –

+0

아, 네 말이 맞아! 나는 그것을 완전 함을 위해 던져 넣었으나 이제는 조금 더 생각할 필요가 있음을 깨닫는다. – bearoplane

관련 문제