Function.apply calls a function on a given object, using eval.

Function.apply is only defined for browser that do not already support it natively. The code for Function.apply in Prototype is based on youngpup’s implementation

Syntax


  Function.apply( object, parameters );

youngpup’s description

youngpup has specified in his FAQ , that all content on his website has been released under a Creative Commons Attribution 2.0 licence, which should make any use of the quotation below o.k. as long as something along the lines of this attribution statement is preserved.

Here is an implementation of the extremely useful Function.apply javascript method for browsers which do not support it.

Basically, what it allows you to do is write a function which acts as proxy for some other arbitrary function whose argument list is not known. One case where this is useful is the implimentation of event listeners.

The eval call is ugly, but this is one of those cases where that function is nice to have around. There is no other way to accomplish this for an unknown number of arguments otherwise. And remember, this code only runs in cases where Function.apply does not exist natively. Basically, IE5.0, Netscape 3, and some other minor ones.

When I wrote this, I was principally concerned with IE5. However, Function.apply is not in the official ECMA spec, so the hack may become more useful in years to come.