命名IIFE和立即调用名称函数之间的区别? [英] Difference between a named IIFE and calling a name function immediately?

查看:236
本文介绍了命名IIFE和立即调用名称函数之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和IIFE之间是否存在差异

Is there any difference between and IIFE

(function foo () {
    var var_of_concern;
}());

和普通函数

function foo () {
   var var_of_concern;
}
foo();

关注我的警告是,如果我从IIFE或函数中没有通过任何内容,将会IIFE会让记忆保持更长时间?

The caveat that concerned me, was if I pass nothing out of either the IIFE or the function, will the IIFE keep the memory alive longer?

推荐答案

相反,虽然这可能不是一个严重的问题。

The opposite, though it's probably not a serious concern.

这两个在语法上是不一样的。第二个声明一个函数并将其绑定到本地符号foo。在函数调用之后,该函数将保留。

The two are syntactically not the same. The second declares a function and binds it to the local symbol "foo". That function will remain after the function call.

IIFE表单在语法上是单个表达式声明。第二种形式涉及两个语句,一个函数声明语句和一个表达式语句(函数调用)。

The IIFE form is syntactically a single expression satement. The second form involves two statements, a function declaration statement and an expression statement (the function call).

函数调用处理的方式局部变量声明有 nothing 与函数对象的形成方式有关。如果您的示例中的两个函数都相同,那么在函数调用中为局部变量分配该空间的方式没有区别。

The way that a function call handles local variable declarations has nothing to do with how the function object came into being. If both functions in your example are the same, then there's no difference to how that space is allocated for the local variables in a function call.

edit —键语法的区别在于:新语句的 start 中的关键字 function 引入了函数声明语句。该语法形式不提供立即调用。也就是这样:

edit — the key syntactic difference is this: the keyword function at the start of a new statement introduces a function declaration statement. That syntactic form does not provide for immediate invocation. That is, this:

function hello() {
  // some code
}();  // <---- ERROR

是语法错误。

函数关键字出现在任何其他上下文(以及任何有效的上下文)中时,它是一个函数宣言—它是一个函数实例化(或函数定义;我必须检查规范)表达式。这些都可以成为JavaScript中表达式的一部分:

When the function keyword appears in any other context (well, any valid context), then it's not a function declaration — it's a function instantiation (or function definition; I'd have to check the spec) expression. These are all things that can be part of an expression in JavaScript:

 5
 "hello"
 false
 (2 + 5)
 (function() { alert("Hi!"); })

请注意,最后一个示例涉及括号 - 通常用于解除看看函数声明!解析器的行为。该左括号表示函数关键字不出现在语句的绝对开头,因此它只是一个函数实例化表达式。

Note that the last example involves parentheses - that's commonly done to "defuse" the "Oh look a function declaration!" behavior of the parser. That opening parenthesis means that the function keyword does not appear at the absolute beginning of the statement, so it's therefore just a function instantiation expression.

这篇关于命名IIFE和立即调用名称函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆