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();
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With