您似乎无法立即将调用的函数表达式设置为变量:
var foo = function() {
alert();
}(); // Immediately alerts
foo(); // Returns "Uncaught TypeError: foo is not a function"
Run Code Online (Sandbox Code Playgroud)
foo原来是未定义的 - 但为什么呢?有没有办法实际保存对立即调用函数的引用?
您似乎无法立即将调用的函数表达式设置为变量
那是不对的
foo原来是未定义的 - 但为什么呢?
您提供的代码将IIFE 的返回值分配给foo.
如果你有:
var foo = function() {
alert();
return 5;
}();
Run Code Online (Sandbox Code Playgroud)
foo会有一个值5.
有没有办法实际保存对立即调用函数的引用?
是的,但这不是组织代码的好方法:
var foo;
(foo = function () {
alert('works just fine');
})();
Run Code Online (Sandbox Code Playgroud)
为什么在需要声明函数时需要立即调用表达式:
function foo() {
alert();
}
Run Code Online (Sandbox Code Playgroud)
然后调用函数:
foo();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |