2012-02-08 2 views
4

Modernizr 소스 코드에서이 발췌문을 찾았습니다. 이 call.call를 사용할 필요가 왜 documentCreateElement.call(scopeDocument,nodeName)하지 않는 것을 성취하는 무엇 단지 call 반대로 나는javascript에서 call.call이 수행하는 작업

var documentCreateElement = scopeDocument.createElement, documentCreateDocumentFragment = scopeDocument.createDocumentFragment; 

// shiv the document 
for (var i = 0, elements = html5.elements, l = elements.length; i < l; ++i) { 
    call.call(documentCreateElement, scopeDocument, elements[i]); 
} 

// shiv the document create element method 
scopeDocument.createElement = function (nodeName) { 
var element = call.call(documentCreateElement, scopeDocument, nodeName); 

궁금? 사전에

덕분에

+0

확실하게 이것은 '호출'이 무엇인가에 달려 있습니까? 'documentCreateElement.call (...)'은'documentCreateElement'를 호출합니다; 그러나'call.call'은'call'을 호출하므로'call.call (documentCreateElement, ...)''call'이'Function.prototype.call' 인 경우에만'documentCreateElement'를 호출합니다 - 이름에도 불구하고 그렇지 않습니다. – ruakh

+0

(조금 덜 불투명하게하려면 : 코드가'CALL.call (documentCreateElement, ...)'라고 가정하십시오. 여전히'documentCreateElement.call (...) '과 동일하다고 생각하겠습니까? 변수'CALL'의 이름이'call'로 변경 되었기 때문에 함수 객체의'call' 메쏘드의 복사본이라는 의미는 아닙니다.) – ruakh

+0

@ruakh [source code] (http://www.modernizr.com/downloads/modernizr-2.5.2.js). 'call' ->'Date.call' ->'Function.prototype.call'입니다. –

답변

1

예, 그것은 documentCreateElement 기능의 맥락에서 .call 함수를 호출합니다. 그래서 궁극적으로는 같은입니다

...

documentCreateElement.call(scopeDocument, nodeName); 

나는 그들은 아마 그냥 얻는 경우에 call 방법을 캐시 Function.prototype.call에 대한 참조

var call = Function.prototype.call 

같은 곳이 있다고 가정 Function.prototype에 덮어 씁니다.


편집 : 아래의 지적

@ruakh으로 Function.prototype.call 덮어 쓸 경우도 Function.prototype에 의존하기 때문에, 다음 call.call이 작동하지 않을 것입니다.

documentCreateElementdocument.createElement 방법에 대한 참조이며, 그 방법은 호스트 오브젝트, 그래서 그것의 프로토 타입 체인에 Function.prototype을 포함 할 것이라는 보장은 없다.

이렇게하면 호스트 개체에 .call을 사용할 수 있습니다.

+1

그건 내 질문의 일종, "그 documentCreateElement.call (scopeDocument, nodeName)을 달성하는 것은 무엇입니까?" call.call을 사용하는 이유는 궁금합니다. – user772110

+0

사실,'Function.prototype.call'으로 해석되는'var call = Date.call;'입니다. –

+0

@ user772110 : 업데이트했습니다. 필자는'Function.prototype.call'이 다른 코드에 의해 덮어 쓰여질 경우를 대비하고 있습니다. –

1

call.call은 사용자 정의 함수 call을 다른 컨텍스트으로 호출합니다.

call은 기본 JavaScript 기능입니다. 그것은 매우 혼란이다, 자바 스크립트의 기능을 일류 시민이기 때문에, 당신은 함수에 호출 할 수있는 기능, 그리고 그것은 call를 불렀다 : P

call의 첫 번째 매개 변수는 상황, 어떤 this 정상적으로입니다 호출 된 함수에서 참조하십시오.

function doit() { 
    console.log(this.myvalue); 
} 

function callit(context) { 
    doit.call(context); 
} 

callit({ "myvalue": "a value"}); // a value 
var obj = { 
    "stuff" : "more stuff", 
    "myvalue": "some value" 
}; 
callit(obj); // some value 

그래서 documentCreateElement.call(scopeDocument,nodeName)은 기본적으로 documentCreateElement(nodeName) 않고 ​​scopeDocumentdocumentCreateElement 점에서 this 예를 들면 다음과 같습니다. 게시 한 예제 코드가 call을 잘 사용하고 있는지 궁금 할 수 있습니다. 내가 틀린 장소에서 잘못 사용하면 항상 매우 복잡해집니다 ~ _ ~

관련 문제