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中,我们可以仅使用花括号({})并使用const或let来获得相同的效果。
Thank you for reading and happy coding!
感谢您的阅读和愉快的编码!
iife 立即执行函数