Wade Wade - 6 months ago 34
Javascript Question

Javascript apply source code

So I know what the

apply()
function does in javascript, but if you were to implement it on your own, how would you do that? Preferably don't use bind, since that's pretty dependent on apply.

NOTE: I'm asking out of curiosity, I don't want to actually do this. Please stop downvoting, if you're not curious then just ignore it.

Answer

You could do it with eval:

Function.prototype.myApply = function(thisVal, args) {
    return eval('this.call(thisVal' + args.map(function(arg, idx) { return ', args[' + idx + ']' }).join('') + ')');
};

…but please don’t do this. The browser-supplied apply implementation ought to be sufficient.