自我调用功能未定义 [英] Self invoking function is undefined
问题描述
如果我声明一个函数literal:
var x = function(){
alert('hi' );
};
console.log(x); //返回功能代码。
然而:
var x =(function(){
alert('hi');
})();
console.log(x); //返回undefined?
我不明白为什么会发生这种情况。是不是编写一个函数作为一个文字的点是仍然能够通过它的变量引用名称来访问它?我知道这可能很傻,但我只是学习JavaScript,所以不要太苛刻。
返回任何东西,所以它的返回值是 undefined
。 自执行函数被执行,函数不是存储在任何地方 - 只有它的返回值能够存活(以及函数设置/修改的任何外部变量)。
例如,这段代码相当于 var x ='hi';
: var x =(function(){
返回'hi';
})();
自调用函数的目的通常是创建一个新的作用域,当在循环中创建回调函数时:
for(var i = 0; i <5; i ++){
window.setTimeout(function(){alert('i ='+ i);},1000 * i);
}
这会使用相同的 i
在所有回调中,所以它会提示 i = 5
5次。
<$ c (函数(){alert('i ='+ i); $ c> for(var i = 0; i <5; i ++){
(function(i){
window.setTimeout },1000 * i);
})(i);
$ b通过使用自动执行函数,我们创建一个新的范围,从而创建一个新的i
在每个循环中。
自执行函数的另一个用途是创建一个新的作用域,其中某些变量是确保可用并设置为正确的值:
(function($,window,undefined){
/ /下面总是适用:
// $ === jQuery
// window ===全局对象[假设函数在全局范围内执行]
// undefined是好吧,未定义 - 在某些js引擎中,有人可以重新定义它
})(jQuery,this);
If I declare a function literal:
var x = function(){ alert('hi'); }; console.log(x); // returns the function code.
However:
var x = (function(){ alert('hi'); })(); console.log(x); // returns undefined?
I don't understand why this happens. Isn't the point of writing a function as a literal is to still be able to access it by its variable reference name? I know this may be silly but I'm just learning javascript so don't judge too harshly.
解决方案Your function does not return anything, so its return value is
undefined
.A self-executing function is executed and the function is not stored anywhere - only its return value survives (and any external variables the function sets/modifies).
For example, this code would be equivalent to
var x = 'hi';
:var x = (function(){ return 'hi'; })();
The purpose of self-invoking functions is usually to create a new scope, e.g. when creating callback functions in a loop:
for(var i = 0; i < 5; i++) { window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i); }
This would use the same
i
in all callbacks so it would alerti = 5
5 times.for(var i = 0; i < 5; i++) { (function(i) { window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i); })(i); }
By using a self-executing function we create a new scope and thus a new
i
in each loop.Another use of self-executing functions is to create a new scope where certain variables are ensured to be available and set to the correct value:
(function($, window, undefined) { // here the following always applies: // $ === jQuery // window === the global object [assuming the function was executed in the global scope] // undefined is well, undefined - in some js engines someone could have redefined it })(jQuery, this);
这篇关于自我调用功能未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!