最近,我通过调用console.log查看了firebugs console.log.toString()的代码,得到了以下结果:
function () { return Function.apply.call(x.log, x, arguments); }只要我理解,Function.apply就会被调用,它的this引用x.log,参数是x和arguments。由于Function.apply本身调用函数,这将导致调用x.log,其this引用x和arguments作为参数。
这就引出了我的问题:是否有任何理由这样称呼Function.apply而不是仅仅使用Function.prototype.apply?或者换句话说,上面的和return x.log.apply(x, arguments)之间有什么区别吗?
编辑:,因为它是开源的,所以我快速查看了firebug源代码并找到了创建它的地方(consoleInjector.js,第73行):
// 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的第一条评论中提到的,但我仍然不完全理解。我可能会对此做进一步的研究。
发布于 2013-02-13 21:14:06
考虑到这一点:
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]规则仍然适用:
var f = function () {};
f.apply = "nubbits";
f.apply(/* err */);当然,我认为改变apply的行为是“有问题的代码”(尤其是以一种不兼容的方式),但这两种形式可能有所不同。就我个人而言,我不适应这种假设的情况,我在代码中使用f.apply。
https://stackoverflow.com/questions/14863171
复制相似问题