最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what does fn.apply(fn, []) do? - Stack Overflow

programmeradmin0浏览0评论

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();

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();
Share Improve this question edited Dec 5, 2014 at 19:25 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Dec 5, 2014 at 19:21 ShaneShane 5,69715 gold badges57 silver badges82 bronze badges 2
  • That call does execute fn in a different this context, that being the function object itself. – Pointy Commented Dec 5, 2014 at 19:26
  • I would remend never doing something like this in production. – tengbretson Commented Dec 5, 2014 at 19:56
Add a ment  | 

2 Answers 2

Reset to default 8

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/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.

发布评论

评论列表(0)

  1. 暂无评论