Yin*_*ang 5 javascript function apply
我最近console.log通过调用查看了firebugs的代码,console.log.toString()得到了这个:
function () { return Function.apply.call(x.log, x, arguments); }
Run Code Online (Sandbox Code Playgroud)
只要我明白这导致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);
Run Code Online (Sandbox Code Playgroud)
我现在几乎可以肯定,这与Function我在一个不同的范围有关,这是我在第一次评论pst的答案时所说的,但我仍然不完全理解它.我可以对此进行一些进一步的研究.
小智 6
考虑一下:
Function.hasOwnProperty("apply") // false
Function.apply == Function.prototype.apply // true
Function.__proto__ == Function.prototype // true in FF which exposes proto
Run Code Online (Sandbox Code Playgroud)
所以 Function.apply 有效,因为 Function 的 [[prototype]] 是Function.prototype。在这种情况下,两者都应该按预期工作。
但是,请考虑正常的[GetProperty]规则仍然适用:
var f = function () {};
f.apply = "nubbits";
f.apply(/* err */);
Run Code Online (Sandbox Code Playgroud)
当然,我会认为这是“有问题的代码”,以改变行为apply(特别是在不兼容的方式),但它可能是这两种形式的不同..我个人并不适应这种假设的情况,我用f.apply我的代码.