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

I have a piece of code that takes fn

as an argument and stores it in a property object

.

var obj = {};

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

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

      

What I don't understand is the code fn.apply(fn,[])

and its purpose. We usually use method call

and apply

when we want to execute fn

in another this/context

.

But what is doing here fn.apply(fn, [])

? It's confusion why I can't just do

obj["name"] = fn();

      

+3


source to share


2 answers


fn.apply(fn, [])

calls a function stored in fn

, with context (value this

when the function is executed) fn

and arguments contained in []

(no arguments).

It seems odd to call it apply

that way when it would be equivalent to calling fn.call(fn)

.



fn()

would not be a suitable replacement as it fn()

will be executed in the global context, which means that the value this

inside the function will be window

(assuming it's in a browser environment).

+6


source


Here's an example showing how it could 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);

      

Output:



yay!
undefined

      

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

This can be useful depending on the context. The basic idea is that you are always this

equal to the function itself, not the global context.

+2


source







All Articles