When I was implementing the online customer support chat system's popup effect JavaScript SDK, the SDK code that was publicly exposed was in the form of a self-executing function.
An immediately-invoked function expression (IIFE) is a function that is defined and executed immediately. The syntax for an IIFE is as follows:
(function() {
// function body
})();
or:
(function() {
// function body
}());
IIFEs can be used to encapsulate your JavaScript code, preventing the definition of variables in the global scope and thus avoiding variable name conflicts.
For example, you can use an IIFE to define local variables within the function and avoid defining variables in the global scope.
For example:
(function() {
// define local variables here
const myLocalVariable = 'hello';
// use the local variable
console.log(myLocalVariable);
})();
This allows you to define local variables within the IIFE and avoid defining variables in the global scope.
IIFEs can also accept parameters, such as:
(function(param1, param2) {
// use function parameters here
console.log(param1, param2);
})('hello', 'world');
This allows you to pass parameters to an IIFE.
If the passed parameter is the window object If the window object is passed to an IIFE and a property is assigned to the window object, the property becomes a global variable.
For example, you can define a global variable using the following code:
(function(global) {
global.myGlobalVariable = 'hello';
})(window);