在JavaScript中,为什么可以';我不能立即调用函数声明吗?
只有函数表达式可以立即调用:在JavaScript中,为什么可以';我不能立即调用函数声明吗?,javascript,function-declaration,self-invoking-function,function-expression,Javascript,Function Declaration,Self Invoking Function,Function Expression,只有函数表达式可以立即调用: (function () { var x = "Hello!!"; // I will invoke myself })(); 但不是函数声明?这是因为函数声明被挂起并且已经立即执行了吗 编辑:我正在引用的资源 不确定您的确切意思-如果您以显示的方式运行函数声明,它仍将立即执行 (函数declaredFn(){ document.getElementById('result').innerHTML='executed'; }()); 以清除混
(function () {
var x = "Hello!!"; // I will invoke myself
})();
但不是函数声明?这是因为函数声明被挂起并且已经立即执行了吗
编辑:我正在引用的资源
不确定您的确切意思-如果您以显示的方式运行函数声明,它仍将立即执行
(函数declaredFn(){
document.getElementById('result').innerHTML='executed';
}());代码>
以清除混淆
什么是函数声明
// this is function declaration
function foo(){
// code here
}
或
如果你这么做的话,马上就叫它
function foo(){
// code here
}()
什么是函数表达式
// this is a function expression
var a = function foo(){
// code here
};
或
在第二种情况下,您创建了一个匿名函数。您仍然可以通过变量a
引用该函数。因此,您可以执行a()
调用函数表达式
var a = (function (){
// code here
}());
变量a与函数结果一起存储(如果从函数返回),并丢失对函数的引用
在这两种情况下,您都可以立即调用函数,但结果与上面指出的不同。:
“…表达式后面的参数表示表达式是要调用的函数,而语句后面的参数与前面的语句完全不同,只是一个分组运算符(用作控制计算优先级的手段)。”
因此,您需要将函数编写为
(function doSomething() {})();
因为这告诉解析器将其作为函数表达式而不是函数声明进行计算。然后您所做的就是立即调用表达式。这不是函数声明,如果您这样做,它将导致引用错误。抱歉,我只是想澄清一下,我知道只有函数表达式可以立即调用,但您不能立即调用函数声明。我想知道为什么会这样。在parens中封装function(){}
使其成为表达式。function x(){}与var x=function(){}相同,显式var“返回”void而不是赋值。这就是为什么你不能说警报(VARx=1),但你可以说警报(x=1);函数也是如此。稍后是否可以在事件侦听器中再次调用此IIF?
var a = (function (){
// code here
}());
// While this function declaration is now syntactically valid, it's still
// a statement, and the following set of parens is invalid because the
// grouping operator needs to contain an expression.
function foo(){ /* code */ }(); // SyntaxError: Unexpected token )
// Now, if you put an expression in the parens, no exception is thrown...
// but the function isn't executed either, because this:
function foo(){ /* code */ }( 1 );
// Is really just equivalent to this, a function declaration followed by a
// completely unrelated expression:
function foo(){ /* code */ }
( 1 );
(function doSomething() {})();