What does call.call do in javascript

Found this passage in Modernizr source code.

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); 

I was wondering why use call.call , not just call What does the execution of documentCreateElement.call(scopeDocument,nodeName) ?

Thanks in advance

+4
source share
2 answers

Yes, it calls the .call function from the context of the documentCreateElement function.

So, in the end, it's the same as ...

 documentCreateElement.call(scopeDocument, nodeName); 

I assume that somewhere there is a link to Function.prototype.call , for example

 var call = Function.prototype.call 

They probably cache the call method in case it is overwritten by Function.prototype .


EDIT:

As @ruakh says below, if Function.prototype.call been overwritten, then call.call will not work, as it also relies on Function.prototype .

documentCreateElement is a reference to the document.createElement method, and this method is the host object, so there is no guarantee that it will include Function.prototype in its prototype chain.

This will allow them to use .call for host objects in these cases.

+1
source

call.call calls a user-defined call function with a different context.

call is a built-in JavaScript function. This is a function that you can call for a function, because in JavaScript, functions are first-class citizens, and it's called call , which is very confusing: P

The first parameter to call is the context, regardless of whether this should refer to the function being called. Here is an example:

 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 

So documentCreateElement.call(scopeDocument,nodeName) basically has documentCreateElement(nodeName) , but this in documentCreateElement points to scopeDocument . You may be wondering if the call code you provided is well used. I always find it very difficult if used incorrectly and inappropriately ~ _ ~

+1
source

Source: https://habr.com/ru/post/1395511/


All Articles