首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >call.call在javascript中实现了什么?

call.call在javascript中实现了什么?
EN

Stack Overflow用户
提问于 2012-02-09 06:33:12
回答 1查看 217关注 0票数 4

在Modernizr源代码中找到了这段摘录。

代码语言:javascript
复制
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,而不是只使用calldocumentCreateElement.call(scopeDocument,nodeName)不能实现什么?

提前感谢

EN

回答 1

Stack Overflow用户

发布于 2012-02-09 06:39:31

call.call使用不同的上下文调用用户定义的函数call

call是一个本机JavaScript函数。这是一个你可以在函数上调用的函数,因为在JavaScript中,函数是一等公民,它被称为call,这非常令人困惑:P

call的第一个参数是上下文,无论this应该在被调用的函数中引用什么。下面是一个示例:

代码语言:javascript
复制
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。如果用错了地方,我总会发现~_~非常复杂。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9202568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档