use*_*031 4 javascript function
如果我声明一个函数文字:
var x = function(){
alert('hi');
};
console.log(x); // returns the function code.
Run Code Online (Sandbox Code Playgroud)
然而:
var x = (function(){
alert('hi');
})();
console.log(x); // returns undefined?
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.将函数编写为文字是不是仍然能够通过其变量引用名称来访问它?我知道这可能很傻,但我只是在学习javascript,所以不要过于严厉地判断.
你的函数没有返回任何东西,所以它的返回值是undefined.
执行自执行函数并且函数不存储在任何地方 - 只有它的返回值存活(以及函数设置/修改的任何外部变量).
例如,此代码相当于var x = 'hi';:
var x = (function(){
return 'hi';
})();
Run Code Online (Sandbox Code Playgroud)
自调用函数的目的通常是创建一个新的作用域,例如在循环中创建回调函数时:
for(var i = 0; i < 5; i++) {
window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i);
}
Run Code Online (Sandbox Code Playgroud)
这将i在所有回调中使用相同的内容,因此它会发出i = 55次警报.
for(var i = 0; i < 5; i++) {
(function(i) {
window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i);
})(i);
}
Run Code Online (Sandbox Code Playgroud)
通过使用自执行函数,我们创建了一个新的范围,从而i在每个循环中创建了一个新的范围.
自执行函数的另一个用途是创建一个新的范围,确保某些变量可用并设置为正确的值:
(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);
Run Code Online (Sandbox Code Playgroud)
如果你:
var foo = somefunction;
Run Code Online (Sandbox Code Playgroud)
...然后你分配一个功能foo.
如果你:
var foo = somefunction();
Run Code Online (Sandbox Code Playgroud)
......那么你的函数的返回值赋给调用到foo
你的功能:
function(){
alert('hi');
}
Run Code Online (Sandbox Code Playgroud)
...没有return声明,所以它会回来undefined.
| 归档时间: |
|
| 查看次数: |
1699 次 |
| 最近记录: |