Call the function now

This article focuses on the meaning, usage, and main scenarios of using immediate or self-executing anonymous functions. The previous articles in this series focused on scopes, prototypes, and execution contexts. This article also serves as a bridge between the two. If you’re interested, check out the portal

directory

  • Understand immediate call function expressions
  • Error: Call function expression immediately
  • 3. Use the correct posture for calling functions immediately
  • 4. Common usage scenarios
  • Write in the last

Understand immediate call function expressions

1.1 Mind mapping

1.2 What is immediate Call?

Before going into more detail, let’s talk about the term “self-executing”. This article may not be completely correct about this function, everyone has a different understanding of it, we use immediate call ~ here

Call now:

  • As the name implies, this expression is aThe creation is executed immediately.
  • Is one that is executed immediately when definedJavaScript function.
(function (x) {
    console.log('x + x = ', x + x); }) (5) // x + x = 10
Copy the code

This is a design pattern called self-executing anonymous functions, which has two main parts:

  1. The first part is enclosed in the parenthesis operator(a)Is an anonymous function with a separate lexical scope. This not only avoids external access to variables in this IIFE, but also does not pollute the global scope.
  2. The second part is used again(a)Creates an immediate function expression where the JavaScript engine will execute the function directly.
1.3 Core Issues

When you declare a function, can you execute it immediately by putting parentheses after it?

var foo = function(){ 
	console.log('corner'); } ();// The afterlight succeeds!
 
/ /... Does that mean adding a parenthesis automatically does that?
function(){
	console.log(' 'Corner); } ();// Uncaught SyntaxError: Function statements require a function name
/ /? Need another function name? Isn't it called self-executing anonymous functions?

// I added the function name
function foo(){
	console.log('corner'); } ();// Uncaught SyntaxError: Unexpected token ')'
Copy the code

Obviously, the second and third items in this example are incorrect, and the contents of the error are different, so what is the problem?

Error: Call function expression immediately

Sometimes, when we call a function immediately after we define it, we cannot enclose parentheses directly after the function definition, which causes a syntax error. The syntax error is that the function keyword can be used as either a statement or an expression, as in the following example:

/ / statements
function fn() {};

/ / expression
var fn = function (){};
Copy the code

To avoid parsing ambiguity, the JS engine specifies that if a function appears at the beginning of a line, it will be parsed as a statement. Therefore, when the JS engine sees the function keyword at the beginning of the line, it considers this paragraph to be a function definition and should not end with parentheses, which it considers to be just grouping operators.

// The following function is syntactically ok, but is still just a statement
// Parentheses () will still give an error because grouping operators need to contain expressions
 
function foo(){ /* code */} ();// SyntaxError: Unexpected token )
 
// But if you pass an expression in bracket (), no exception will be thrown
Foo, however, will not be executed
function foo(){ /* code */} (1 );
 
// This is exactly the same as declaring an unrelated expression after a function declaration:
function foo(){ /* code */ }
 
( 1 );
Copy the code

3. Use the correct posture for calling functions immediately

To solve the above problems, it is very simple.

We just need to wrap the entire code in parentheses, because JavaScript parentheses () cannot contain statements, so at this point the parser will parse the code into function expressions instead of function declarations when parsing the function keyword.

3.1 Common posture
// The following two parentheses () are executed immediately

(function () { /* code */ } ()); // This is recommended
(function () { /* code */}) ();// But this can also be used
Copy the code
3.2 Unusual Gestures (1)
// Since parentheses () and JS &&, xor, comma and other operators are disambiguating function expressions and function declarations
// So once the parser knows that one of them is already an expression, the others default to expressions

var i = function() {
    console.log('corner')
}(); / / corner

true && function() {
    console.log('corner')
}(); / / corner

0.function() { console.log('corner') }(); / / corner
Copy the code
3.3 Unusual Gestures (2)
// If you don't care about the return value, or are not afraid of being difficult to read
// You can even add unary operations before function

/ / a bool
var res1 = !function () {
    console.log('corner'); } ()console.log('res1:', res1); / / in my true

/ / number
var res2 = +function () {
    console.log('corner'); } ()console.log('res2:', res2); / / corner NaN

/ / not by location
varRes3 = ~function () {
    console.log('corner'); } ()console.log('res3:', res3); / / corner NaN
Copy the code
3.4 Unusual Gestures (3)

There is also a case where the new and void keywords are used, but this is less common.

void function() {
    console.log('corner'); } ();new function() {
    console.log('corner'); } ();Copy the code

4. Common usage scenarios

4.1 Quarantine scope

The most common feature of IIFE is isolation scope. Prior to ES6, JS did not have the concept of block-level scope, so function scope is needed to simulate.

For example:

var currentTime = (function () {
    var time = new Date(a);var year  = time.getFullYear()
    var month = time.getMonth()+1;
    var date  = time.getDate();
    var hour  = time.getHours();
    var min   = time.getMinutes();
    return year + The '-' + month + The '-' + date + ' ' + hour + ':'+ min; }) ()Copy the code

You can still declare variables of the same name elsewhere

4.2 Lazy Functions

In order to be compatible with modern browsers and IE browsers, we need to make a judgment on the browser environment:

var addEvent = (function(){
    if(window.addEventListener) {
        return function(type, el, fn) {
            el.addEventListener(type, fn, false); }}else if(window.attachEvent) {
        return function(type, el, fn) {
            el.attachEvent('on'+ type, fn); }}}) ();Copy the code
4.3 Use closures to save state

I’ll use just one example here as a reminder for my next article, closures in JavaScript

var elems = document.getElementsByTagName('a');

for (var i = 0; i < elems.length; i++) {
    (function (lockedInIndex) {
        elems[i].addEventListener('click'.function (e) {
            e.preventDefault();
            alert('I am link #' + lockedInIndex);
        }, 'false');
    })(i);
}
Copy the code
Pay attention to

When a function becomes a function expression that executes immediately, variables in the expression cannot be accessed externally.

(function () { 
    var name = "Barry"; }) ();// The variable name cannot be accessed externally
name // Throw an error: "Uncaught ReferenceError: Name is not defined"
Copy the code

Assigning the IIFE to a variable stores not the IIFE itself, but the results returned by the IIFE execution.

var result = (function () { 
    var name = "Barry"; 
    returnname; }) ();// IIFE returns the following result:
result; // "Barry"
Copy the code

reference

  • Why should JS execute functions immediately, and what is the point of existence?
  • IIFE (Call function expressions now)

Write in the last

JavaScript internal power series:

  1. This, call, apply
  2. From Prototype to Prototype Chain, Series ii
  3. From scope to scope chain, Series 3
  4. Execution Context in JavaScript (4)
  5. Variable objects in JavaScript (5)
  6. In this paper,
  7. Closures in JavaScript

About me

  • Name: Afterglow
  • WX: j565017805
  • JS addiction, the level is limited, modestly learning

Other precipitation

  • JavaScript version of LeetCode solution
  • Front-end advanced notes
  • CSDN

If you see the end, please bookmark, like and comment!! Continue to update, your three even is my biggest power, humbly accept the big men’s criticism and advice, mutual encouragement!