admin管理员组文章数量:1429946
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 differentthis
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
2 Answers
Reset to default 8fn.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.
本文标签: javascriptwhat does fnapply(fn) doStack Overflow
版权声明:本文标题:javascript - what does fn.apply(fn, []) do? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745557347a2663265.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论