首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Function.apply对Function.prototype.apply

Function.apply对Function.prototype.apply
EN

Stack Overflow用户
提问于 2013-02-13 21:08:48
回答 1查看 2.4K关注 0票数 6

最近,我通过调用console.log查看了firebugs console.log.toString()的代码,得到了以下结果:

代码语言:javascript
运行
复制
function () { return Function.apply.call(x.log, x, arguments); }

只要我理解,Function.apply就会被调用,它的this引用x.log,参数是xarguments。由于Function.apply本身调用函数,这将导致调用x.log,其this引用xarguments作为参数。

这就引出了我的问题:是否有任何理由这样称呼Function.apply而不是仅仅使用Function.prototype.apply?或者换句话说,上面的和return x.log.apply(x, arguments)之间有什么区别吗?

编辑:,因为它是开源的,所以我快速查看了firebug源代码并找到了创建它的地方(consoleInjector.js,第73行):

代码语言:javascript
运行
复制
// Construct a script string that defines a function. This function returns
// an object that wraps every 'console' method. This function will be evaluated
// in a window content sandbox and return a wrapper for the 'console' object.
// Note that this wrapper appends an additional frame that shouldn't be displayed
// to the user.
var expr = "(function(x) { return {\n";
for (var p in console)
{
    var func = console[p];
    if (typeof(func) == "function")
    {
        expr += p + ": function() { return Function.apply.call(x." + p +
            ", x, arguments); },\n";
    }
}
expr += "};})";

// Evaluate the function in the window sandbox/scope and execute. The return value
// is a wrapper for the 'console' object.
var sandbox = Cu.Sandbox(win);
var getConsoleWrapper = Cu.evalInSandbox(expr, sandbox);
win.wrappedJSObject.console = getConsoleWrapper(console);

我现在几乎可以肯定,这与Function的范围不同有关,这也是我在对pst的第一条评论中提到的,但我仍然不完全理解。我可能会对此做进一步的研究。

EN

回答 1

Stack Overflow用户

发布于 2013-02-13 21:14:06

考虑到这一点:

代码语言:javascript
运行
复制
Function.hasOwnProperty("apply")             // false
Function.apply == Function.prototype.apply   // true
Function.__proto__ == Function.prototype     // true in FF which exposes proto

所以Function.apply可以工作,因为函数的[原型]是Function.prototype。在这种情况下,两者都应该按需要工作。

但是,考虑到正常的[GetProperty]规则仍然适用:

代码语言:javascript
运行
复制
var f = function () {};
f.apply = "nubbits";
f.apply(/* err */);

当然,我认为改变apply的行为是“有问题的代码”(尤其是以一种不兼容的方式),但这两种形式可能有所不同。就我个人而言,我不适应这种假设的情况,我在代码中使用f.apply

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

https://stackoverflow.com/questions/14863171

复制
相关文章

相似问题

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