函数调用javascript [英] Function call javascript
问题描述
我调用了helloworld并用以下两种不同的方式定义它:
1)With variable
2 )使用函数名itseld
var helloWorld = function(){
return'2';
}
函数helloWorld(){
return'1';
}
alert(helloWorld()); //此警报2,但没有var helloWorld = ....时,警报1。
任何人都可以解释为什么调用var helloWord =?而不是函数helloWorld()?
谢谢!!
为什么要调用var helloWord =?而不是函数helloWorld()?
因为函数
定义将会是悬挂
到顶部。而作业仍然在同一个地方。所以它会越过被覆盖
。
这就是解释器看到代码的方式,
函数helloWorld(){
return'1';
}
var helloWorld;
//上面的函数在这里被覆盖。
helloWorld = function(){
return'2';
}
alert(helloWorld());
I called helloworld and defined it with below two different ways:
1) With variable
2) With function name itseld
var helloWorld = function() {
return '2';
}
function helloWorld() {
return '1';
}
alert (helloWorld()); // This alert 2, but in absence of "var helloWorld = ....", it alert "1".
Can anyone please explain reason why it's calling var helloWord = ? and not function helloWorld () ?
Thank You !!
why it's calling var helloWord = ? and not function helloWorld () ?
Because functions
definitions will be hoisted
to the top. And the assignments remains in the same place. So it is getting overridden
.
This is how the interpreter sees the code,
function helloWorld() {
return '1';
}
var helloWorld;
//the above function is getting overridden here.
helloWorld = function() {
return '2';
}
alert (helloWorld());
这篇关于函数调用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!