在Modernizr源代码中找到此摘录.
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);
我想知道为什么有必要使用call.call,而不是只调用documentCreateElement.call(scopeDocument,nodeName)没有完成什么?
提前致谢
最佳答案 call.call使用不同的上下文调用用户定义的函数调用.
call是本机JavaScript函数.这是一个你可以在一个函数上调用的函数,因为在JavaScript中函数是一等公民,它叫做call,这非常令人困惑:P
调用的第一个参数是上下文,无论在被调用函数中应该引用什么.这是一个例子:
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),但documentCreateElement中的this指向scopeDocument.您可能想知道您发布的示例代码是否充分利用了调用.如果错误使用并且不合适,我总觉得它非常复杂~~~