iife 立即执行函数_JavaScript中的IIFE(立即调用函数表达式)

iife 立即执行函数

IIFE- Immediately Invoked Function Expression is a way to execute functions immediately, as soon as they are created. This is a good way to protect the scope of your function and the variables within it.

IIFE - mmediately nvoked˚Fê上的表达是尽快在创建立即执行功能的方法。 这是保护函数范围及其中变量的好方法。

It is a design pattern which is also known as a Self-Executing Anonymous Function

这是一种设计模式,也称为自执行匿名函数

(function () {
// Write your js code here
})();

Named IIFE with parameters

带有参数的IIFE命名

(function showCurrentDate(date) {
console.log('I am from IIFE', date)
})(new Date());

Why IIFE is so useful?

为什么IIFE如此有用?

IIFE is the most better way to avoid:* Polluting global variables* Overwrite global scope

IIFE是避免以下情况的最佳方法:*污染全局变量*覆盖全局范围

var name = 'Pradeep';
(function () {
var name = 'chauhan';
console.log("Hello " + name);
})();
console.log("Hello " + name);Output:
Hello Chauhan
Hello Pradeep

Another use case of IIFE is, it can be used as a closure

IIFE的另一个用例是,它可用作闭包

const generateUniqueId = (function() {
var counter = 0;
return function() {
++counter;
return `JSN_${counter}`;
};
})();
console.log(generateUniqueId()); //JSON_1
console.log(generateUniqueId()); //JSON_2
console.log(generateUniqueId()); //JSON_3

The counter variable is inaccessible from outside of the IIFE. Except for the function that’s being returned, nobody can read or modify the counter variable.

IIFE外部无法访问该计数器变量。 除了要返回的功能外,没有人可以读取或修改计数器变量。

Note: IN ES6, we can just user curly braces ({}) and use const or let to get the same effect.

注意:在ES6中,我们可以仅使用花括号({})并使用constlet来获得相同的效果。

Thank you for reading and happy coding!

感谢您的阅读和愉快的编码!

翻译自: https://medium.com/@pkchauhan/iife-immediately-invoked-function-expression-in-javascript-4a50c843d8df

iife 立即执行函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值