Function.apply vs Function.prototype.apply

I recently looked at firebugs code console.log, calling console.log.toString()and got the following:

function () { return Function.apply.call(x.log, x, arguments); }

As long as I understand, this calls Function.applyfor a call with it thiswith a link to x.log, and the arguments xand arguments. Since Function.applyhe calls the functions himself, this will lead to a call x.logwith his own this, referring to xand argumentsas his arguments.

Which leads me to my question: is there a reason to call it Function.applythat way and not just use it Function.prototype.apply? Or, in other words, is there a difference between the above and return x.log.apply(x, arguments)?

Change: . Since it is open source, I quickly looked through the source code of firebug and found the place where it was created ( consoleInjector.js , line 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);

Now I’m almost sure that this has Functionto be in a different area, which I said in my first comment on pst , but I still don’t know Fully understand this. I can work on this a bit.

+5
source share
1 answer

Consider this:

Function.hasOwnProperty("apply")             // false
Function.apply == Function.prototype.apply   // true
Function.__proto__ == Function.prototype     // true in FF which exposes proto

So Function.apply works because Function [[prototype]] Function.prototype . In this case, both should work as desired.

However, note that the normal [GetProperty] rules still apply:

var f = function () {};
f.apply = "nubbits";
f.apply(/* err */);

, " " apply ( ), , . f.apply .

+4

All Articles