Javascript 未定义自调用函数

Javascript 未定义自调用函数,javascript,function,Javascript,Function,如果我声明一个函数文字: var x = function(){ alert('hi'); }; console.log(x); // returns the function code. 然而: var x = (function(){ alert('hi'); })(); console.log(x); // returns undefined? 我不明白为什么会这样。将函数作为文本编写的目的不是仍然能够通过其变量引用名访问它吗?我知道这可能很傻

如果我声明一个函数文字:

var x = function(){
        alert('hi');
    };
    console.log(x); // returns the function code.
然而:

var x = (function(){
    alert('hi');
})();

console.log(x); // returns undefined?

我不明白为什么会这样。将函数作为文本编写的目的不是仍然能够通过其变量引用名访问它吗?我知道这可能很傻,但我只是在学习javascript,所以不要太苛刻地判断。

您的函数不返回任何内容,因此其返回值是
未定义的

执行一个自执行函数,该函数不存储在任何地方-只有其返回值(以及函数设置/修改的任何外部变量)存在

例如,此代码相当于
varx='hi'

var x = (function(){
    return 'hi';
})();
自调用函数的目的通常是创建新的作用域,例如,在循环中创建回调函数时:

for(var i = 0; i < 5; i++) {
    window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i);
}
通过使用一个自执行函数,我们在每个循环中创建一个新的作用域,从而创建一个新的
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);
如果你:

var foo = somefunction;
var foo = somefunction();
…然后将函数分配给
foo

如果你:

var foo = somefunction;
var foo = somefunction();
…然后将函数调用的返回值分配给
foo

你的职能:

function(){
    alert('hi');
}
…没有
return
语句,因此它将返回
undefined