Velocity Reviews > Function.call and Function.apply

# Function.call and Function.apply

HopfZ
Guest
Posts: n/a

 08-25-2006
I would like to check if my understanding of the two functions are
correct.

Is this correct? The following three lines are equivalent, for
example, [1] can be replaced with [2] or [3] anywhere in a script
without changing the return value and without changing any side effect.

[1] var r = o.f(a,b);
[2] var r = o.f.call(o,a,b);
[3] var r = o.f.apply(o,[a,b]);

( o is an object and o.f is a function. )

The following three lines are equivalent:
[1'] var r = g(a,b);
[2'] var r = g.call(this,a,b);
[3'] var r = g.apply(this,[a,b]);

( g is a function, for example,
var g = function(a,b){return [this,a,b];}. )

Lasse Reichstein Nielsen
Guest
Posts: n/a

 08-25-2006
"HopfZ" <(E-Mail Removed)> writes:

> Is this correct? The following three lines are equivalent

....
> [1] var r = o.f(a,b);
> [2] var r = o.f.call(o,a,b);
> [3] var r = o.f.apply(o,[a,b]);

Correct

> The following three lines are equivalent:
> [1'] var r = g(a,b);
> [2'] var r = g.call(this,a,b);
> [3'] var r = g.apply(this,[a,b]);

Only if used where "this" refers to the global object (i.e., the call
is in the global scope or inside a function called in this way).

/L
--
Lasse Reichstein Nielsen - http://www.velocityreviews.com/forums/(E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'