在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,而不是只使用call。documentCreateElement.call(scopeDocument,nodeName)不能实现什么?
提前感谢
发布于 2012-02-09 06:39:31
call.call使用不同的上下文调用用户定义的函数call。
call是一个本机JavaScript函数。这是一个你可以在函数上调用的函数,因为在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),但documentCreateElement中的this指向scopeDocument。您可能想知道您发布的示例代码是否很好地使用了call。如果用错了地方,我总会发现~_~非常复杂。
https://stackoverflow.com/questions/9202568
复制相似问题