iife 立即执行函数_JavaScript中的IIFE:什么是立即调用的函数表达式?

iife 立即执行函数

功能说明 (Function Statement)

A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects. Example:

使用函数声明创建的函数是Function对象,并且具有Function对象的所有属性,方法和行为。 例:

function statement(item){
    console.log('Function statement example '+ item);
  }

函数表达式 (Function Expression)

A function expression is similar to function statement except that function name can be omitted to create anonymous functions. Example:

函数表达式类似于函数语句,不同之处在于可以省略函数名称以创建匿名函数。 例:

var expression = function (item){
    console.log('Function expression example '+ item);
  }

立即调用的函数表达式 (Immediately Invoked Functions Expressions)

A soon as function is created it invokes itself doesn’t need to invoke explicitly. In the below example variable iife will store a string that is returned by the function execution.

一旦创建函数,它便会调用自身,而无需显式调用。 在下面的示例变量iife中,将存储由函数执行返回的字符串。

var iife = function (){
    return 'Immediately Invoked Function Expressions(IIFEs) example ';
  }();
  console.log(iife); // 'Immediately Invoked Function Expressions(IIFEs) example '

The statement before IIFE should always end with a ; or it will throw an error.

IIFE之前的声明应始终以;结尾。 否则会抛出错误。

Bad example:

不好的例子

var x = 2 //no semicolon, will throw error
(function(y){
  return x;
})(x); //Uncaught TypeError: 2 is not a function

为什么要使用立即调用的函数表达式? (Why use Immediately Invoked Functions Expressions?)

(function(value){
    var greet = 'Hello';
    console.log(greet+ ' ' + value);
  })('IIFEs');

In above example when javascript engine execute above code it will create global execution context when it sees code and create function object in memory for IIFE. And when it reaches on line 46 due to which function is Invoked a new execution context is created on the fly and so greet variable goes into that function execution context not into the global this is what makes it unique. This ensures that code inside IIFE does not interfere with other code or be interfered by another code and so code is safe.

在上面的示例中,当javascript引擎执行以上代码时,它将在看到代码并在内存中为IIFE创建函数对象时创建全局执行上下文。 当由于调用了哪个函数而到达第46行时,会立即创建一个新的执行上下文,因此greet变量将进入该函数执行上下文,而不是进入全局变量,这就是使其变得唯一的原因。 This ensures that code inside IIFE does not interfere with other code or be interfered by another code ,因此代码是安全的。

更多信息 (More Information)

翻译自: https://www.freecodecamp.org/news/iife-in-javascript-what/

iife 立即执行函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值