【问题标题】:In JavaScript, why can't I immediately invoke function declarations?在 JavaScript 中,为什么我不能立即调用函数声明?
【发布时间】:2014-10-13 07:15:22
【问题描述】:

只有函数表达式可以立即调用:

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

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

编辑:我引用的资源

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

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

【问题讨论】:

  • function x(){} 与 var x=function(){} 相同,并且显式 var “返回” void 而不是赋值。这就是为什么你不能说 alert(var x=1),但你可以说 alert(x=1);功能相同。

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


【解决方案1】:

Source

"...虽然放在表达式之后的括号表示表达式是要调用的函数,但放在语句之后的括号与前面的语句完全分开,并且只是一个分组运算符(用作控制评估的优先级)。”

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

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

【讨论】:

  • 以后是否可以再次调用此 IIF,例如在事件侦听器中?
【解决方案2】:

为了消除混乱

什么是函数声明

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

//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 与函数的结果一起存储(如果您从函数返回)并丢失对函数的引用。

在这两种情况下,您都可以立即调用一个函数,但结果与上述不同。

【讨论】:

    【解决方案3】:

    不确定你的确切意思 - 如果你以你展示的方式运行一个函数声明,它仍然会立即执行

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

    【讨论】:

    • 这不是函数声明,如果call declaredFn later会导致引用错误。
    • 抱歉,澄清一下,我了解到只有函数表达式可以立即调用,但不能立即调用函数声明。我想知道这是为什么。
    • function () {} 括在括号内使其表达。
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2021-09-04
    • 1970-01-01
    相关资源
    最近更新 更多