3

I read this snippet in the definitive guide:

function not(f)
{
  return function()
  {
    var result=f.apply(this,arguments);
    return !result;
  }
}

What I can't understand is, since this function f is in the closure, it's this is already this, why wouldn't this snippet just directly use var result=f(arguments);?

I even read some calls with undefined/null as the first parameter which I think can completely be replaced with direct call:

...
while(i>len)
{
  if(i in a)
     accumulator=f.call(undefined,accumulator,a[i],i,a);
  i++;
}
...

Why did the author use call() but not direct call? are there any difference between direct function call and call() with undefined as it's first parameter?

1 Answer 1

4
var result=f(arguments);

...Will call f() passing a single argument, the arguments object.

var result=f.apply(this,arguments);

...Will call f() passing the arguments in the arguments object individually (so to speak).

So let's say f() was defined as:

function f(a,b,c) {
    // do something with a, b, c
    return c;
}

Then given three arguments 1,2,3 the direct call with arguments is like this:

f([1,2,3]);

(Note that arguments is array-like; it isn't an actual array.)

Whereas the .apply() version is like this:

f(1,2,3);
Sign up to request clarification or add additional context in comments.

4 Comments

@nnnnnn Thanks! Very clearly explained! But what about the call() with undefined as first argument in the second snippet?
In that case, if the code is not in strict mode, undefined is replaced by the global object (but only where a native function object is being called, it may not work like that for built–in methods or host methods). See ECMA §15.3.4.4 and §13.2.1
Yes, what RobG said. Out of context I couldn't say what benefit that might have for the code snippet you show for .call(). (Seems to be completely unrelated to the reason for using .apply() in the other code snippet.)
Can anyone give speed comparison and the use case when to use what.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.