使用函数表达式而不是函数声明的优点? [英] Advantages to use function expression instead of function declaration?
问题描述
函数表达式与函数声明相比有一个缺点,如果在声明它之前调用它会给出错误。
我只想知道使用函数表达式的优点,因为我似乎只能看到我刚才提到的缺点。我可以用一个例子... 函数表达式: 函数声明: //stackoverflow.com/a/338053/2324107\">很好的答案
警报(FOO()); //错误! foo尚未加载
var foo = function(){return 5; }
警报(FOO()); //警报5.声明在任何代码运行之前加载。
函数foo(){return 5; }
例如下面的代码:
function foo(){
console.log('foo );
函数bar(){
console.log('bar');
}
var myFn = foo;
myFn();
$ b $ setInterval(function(){
if(myFn === foo)myFn = bar;
else myFn = foo;
},5000);
setInterval(function(){
myFn()
},6000);
自从您重新分配一个全局变量后,它将永远不会记录相同的内容,每次innerscope函数都会更改代码:
function foo(){
console.log('foo');
setInterval(function(){
function foo(){
console.log('Changed foo');
}
foo()
},5000)
setInterval(function(){
foo()
},5000)
会记录2个不同的东西。您只能更改当前的作用域函数,而不能更改全局。
As seen here, there are some differences between function declaration and function expression.
A function expression has one disadvantage vs a function declaration, if called before its been declared it will give an error.
I would like to know only the advantages to use a function expression as I only seem to see the disadvantage I just named above. I possible with an example...
function expression:
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
function declaration:
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
Along with that very good answer, the only advantage I can see is dynamically changing a function call.
For example this code :
function foo(){
console.log('foo');
}
function bar(){
console.log('bar');
}
var myFn = foo;
myFn();
setInterval(function(){
if(myFn === foo) myFn = bar;
else myFn = foo;
}, 5000);
setInterval(function(){
myFn()
}, 6000);
It will never log the same thing since you reassign a global variable, every innerscope function will change while this code :
function foo(){
console.log('foo');
}
setInterval(function(){
function foo(){
console.log('Changed foo');
}
foo()
}, 5000)
setInterval(function(){
foo()
}, 5000)
Will log 2 different things. You can only change the current scope function, not the global.
这篇关于使用函数表达式而不是函数声明的优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!