Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does fn.apply(fn, []) do?

Tags:

javascript

I have a piece of code which accepts fn as the argument and stores it in an object property.

var obj = {};

function anotherFn(fn){
   obj["name"] = fn.apply(fn, []);
}

function google(){
    console.log("hello");
}
anotherFn(google);
console.log(obj.name);

What i am not understanding is the fn.apply(fn,[]) code and its purpose. Normally we use call and apply method when we want to execute a fn in a different this/context.

But what does the fn.apply(fn, []) do here?. The confusion is why can't i just do

obj["name"] = fn();
like image 245
Shane Avatar asked Dec 19 '22 08:12

Shane


2 Answers

fn.apply(fn, []) calls the function stored in fn with a context (the value of this while executing the function) of fn, and the arguments contained within [] (no arguments).

It seems odd to call apply in that way, when it would have been equivalent to call fn.call(fn).

fn() would not be an appropriate replacement, as fn() will execute in the global context, which means that the value of this within the function will be window (assuming a browser environment).

like image 78
zzzzBov Avatar answered Dec 31 '22 00:12

zzzzBov


Here's a contrieved sample showing how it can be different:

var obj = {};

function anotherFn(fn){
   obj["name"] = fn.apply(fn, []);
}

function anotherFn2(fn){
   obj["name"] = fn(fn, [])
}

function google() {
    console.log(this.world);
}
google.world = "yay!"

anotherFn(google);
anotherFn2(google);

The output is:

yay!
undefined

jsFiddle: http://jsfiddle.net/c56ja3jL/

Depending on the context, this might be useful. The basic idea is that you always have this equal to the function itself, instead of the global context.

like image 31
steady rain Avatar answered Dec 31 '22 00:12

steady rain