在JavaScript中,为什么我不能立即调用函数声明?

时间:2014-10-13 07:15:23

标签: javascript function-declaration self-invoking-function function-expression

只能立即调用函数表达式:

(function () {
    var x = "Hello!!";      // I will invoke myself
})();

但不是函数声明?这是因为函数声明被提升并且已经立即执行了吗?

编辑:资源我引用

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

http://markdalgleish.com/presentations/gettingclosure/

3 个答案:

答案 0 :(得分:3)

Source

" ...虽然位于表达式后面的parens表示该表达式是一个要调用的函数,但是在语句之​​后放置的parens与前面的语句完全分开,并且只是一个分组运算符(用作意味着控制评估的优先权。)"

// 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() {})();

因为这告诉解析器将它作为函数表达式进行评估而不是函数声明。而你所做的就是立即调用表达式。

答案 1 :(得分:2)

清除混乱

什么是功能声明

// this is function declaration
function foo(){
  // code here
}

OR

//this is ok, but without name, how would you refer and use it
function (){
  // code here
}

立即调用它来执行此操作

function foo(){
  // code here
}()

什么是函数表达式

// this is a function expression
var a = function foo(){
 // code here
};

var a = function (){
  // code here
};

在第二种情况下,您创建了一个匿名函数。您仍然可以通过变量a引用该函数。所以您可以a()

调用函数表达式

var a = (function (){
  // code here
}());

变量a与函数的结果一起存储(如果从函数返回)并丢失对函数的引用。

在这两种情况下,你都可以立即调用一个函数,但结果会有所不同,如上所述。

答案 2 :(得分:1)

不确定你究竟是什么意思 - 如果你以你所显示的方式运行一个函数声明它仍会立即执行

(function declaredFn(){
  document.getElementById('result').innerHTML='executed';
}());
<div id="result"></div>