JavaScript [8] JavaScript function advanced

Article directory

  • Preface
  • Callback
  • recursive function
  • Closure
    • What is a closure function?
    • Three characteristics of closure
    • Disadvantages of closures
    • JavaScript garbage collection mechanism
    • Closure small case
      • Local variables reside in memory for a long time
      • Avoid global variable pollution
      • the existence of private members
  • [ES6] block-level scope
    • What is block scope
    • Function declaration and block scope
  • Function extension
    • [ES6] Destructuring assignment of function parameters
    • [ES6] Arrow functions
      • Basic usage
      • Use attention points
  • Write at the end


Foreword

Hi friends, this article will be included in the column of JavaScript [Front-End Boy Skills]; this column will include some basic knowledge of JavaScript and project practice; I hope you can support it a lot, your support is my creation Momentum; let’s take a look

Callback function

The js code will be executed from top to bottom, but sometimes we need to wait until the end of an operation before proceeding to the next user operation. At this time, we need to use a callback function to control the function of the next operation.

Use the pointer of a function as a parameter of another function. When this parameter is called, the function that is used as a parameter is called a callback function.

function A(callback) {<!-- -->
    callback();
    console.log('main function');
}

function cb(){<!-- -->
    console.log("callback function")
}
A(cb)

Pass the whole function as a parameter

function A(callback) {<!-- -->
    callback();
    console.log('main function');
}


A(function (){<!-- -->
    console.log("callback function")
})

Pass parameters to the callback function

function A(callback) {<!-- -->
    var str = "parameters passed to the callback";
    callback(str);
    console.log('main function');
}

A(function (str){<!-- -->
    //str is to receive the parameters passed by the main function
    console.log("The parameter passed by the main function is", str);
    console.log("callback function");
})

When executing the callback make sure it is a function

function Fn(options, callback) {<!-- -->
    if (typeof callback === "function") {<!-- -->
        callback(options);
    }
}

Example: Encapsulating the each function to simplify the for loop

function each(n,callback){<!-- -->
    for(var i=0;i<n;i ++ ){<!-- -->
        callback(i)
    }
}

each(10,function(i){<!-- -->
    console. log(i)
})

Recursive function

The so-called recursive function is to call this function in the function body. Be careful when using recursive functions, otherwise it will enter an infinite loop.

  • Reference itself directly or indirectly within a function.
  • Every recursive function must have a termination condition.

Find the factorial:

function factorial(c){<!-- -->
  if(c == 1){<!-- -->
      return c;
  }else{<!-- -->
      return c * factorial(c-1);
  }
}
alert(factorial(5));

Multidimensional array traversal:

var new_array=[];
function _getChilds(data){<!-- -->
    if(typeof data != "object" || data == null){<!-- -->
        new_array. push(data);
    }else{<!-- -->
        getChilds(data);
    }
}
function getChilds(data){<!-- -->
    for(var i in data){<!-- -->
        _getChilds(data[i]);
    }
}
var json = {<!-- -->
    "aa" : {<!-- -->"l" : 1,"m" : 3},
    "bb" : 1,
    "cc" : "abc",
    "dd" : true,
    "ee" : null
}
getChilds(json)
console. log(new_array)
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Closure

Closure is a major feature of the JavaScript language, and its main application is to design private methods and variables.

What is a closure function?

Before understanding closures, you need to understand the difference between global scope and local scope. The global variables defined in the global scope can be accessed inside the function, but the local variables defined inside the function (local scope) cannot be accessed outside the function.

  • Concept: A closure is a function that is defined inside an external function and can access variables in the external function.
  • Rationale: Scope chain

A common way to create closures is to create a function inside another function and return:

function fun(num){<!-- -->
    return function (){<!-- -->
        return num;
    }
}
var end = fun(100);
end(); // 100

In the above case, num is a variable inside the fun function, which can only be used inside the fun function, but the returned function also has permission to access num. Therefore, the variables inside the function can be obtained by calling the returned function outside the function

function out (){<!-- -->
   var n = 1;
   return function (){<!-- -->
       return n ++ ;
} }
var fn = out();
console.log(fn()) //1
console.log(fn()) //2
console.log(fn()) //3

Three characteristics of closure

  1. function nested function
  2. Functions can refer to external parameters and variables
  3. Parameters and variables are not garbage collected

Disadvantages of closure

The disadvantage of closures is that they are resident in memory, which will increase memory usage, and improper use can easily cause memory leaks. After the general function is executed, the local active object will be destroyed, and only the global scope is saved in memory. But the case of closures is different.

JavaScript garbage collection mechanism

  1. In JavaScript, if an object is no longer referenced, then this object will be reclaimed by GC.
  2. If two objects refer to each other but are not referenced by a third party, then the two objects that refer to each other will also be recycled.

Closure small case

So what are the benefits of using closures?

  1. Want a local variable to reside in memory for a long time
  2. Avoid global variable pollution
  3. the presence of private members

Local variables reside in memory for a long time

function out (){<!-- -->
    var n = 1;
    return function (){<!-- -->
        return n ++ ;
    }
}
var fn = out();
console. log(fn())
console. log(fn())
console. log(fn())

Find the index of the corresponding element directly in the loop

note/<ul>
  <li>1111111</li>
  <li>1111111</li>
  <li>1111111</li>
</ul>
var lis=document. getElementsByTagName("li");
for(var i=0;i<lis. length;i + + ){<!-- -->
   (function(i){<!-- -->
       lis[i].onclick=function(){<!-- -->
           alert(i);//0 1 2
       }
   })(i)
}
for(var i=0;i<10;i ++ ){<!-- -->
    setTimeout(function(){<!-- -->
        console.log(i); //10
    }, 1000)
}
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Avoid global variable pollution

But when we declare a function, it is actually equivalent to creating a global variable. In the previous example, there are a total of 2 global variables.

Function expression Function self-invocation:

(function(){
})()
 var out = (function(){
    var n1 = 1;
    var n2 = 100;
    return function(){
        n1++;
        n2--;
        return n1 + n2;
} })()
out() // 1
out() // 2

Existence of private members

modular code

var aa=(function(){
   var a=10;
   function aaa(){
       a + + ;
       alert(a);
   }
   function bbb(){
       a + =10;
       alert(a);
   }
   return {
      a:aaa,
      b:bbb
   }
})()
aa.a(); //11
aa.b(); //21
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

The advantage of this is that we cannot access these two functions of bbb aaa outside

  • JavaScript Internal Principles Series – Closures

Because the closure will cause the variables in the function to be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause performance problems of the web page, and may cause memory leaks in IE.

[ES6] block-level scope

What is block scope

The scopes in JS are: global scope and function scope. There is no concept of block scope. ECMAScript 6 (ES6 for short) has added block-level scope.

The block scope is included by { }, and the { } in the if statement and the for statement belong to the block scope.

ES5 has no concept of block scope:

{<!-- -->
  var num = 10;
}
console. log(num) // 10

// After the for loop ends, the variable i will still exist
for(var i = 10; i<5;i ++ ){<!-- --> }
console. log(i); // 5

ES6 block-level scope:

{<!-- -->
  let num = 10;
}
console.log(num) // error: num is not defined

// Since i exists in block-level scope, i can only be used in loop {}
for(let i = 10; i<5;i ++ ){<!-- --> }
console.log(i); // error: i is not defined

Function declaration and block scope

  • In ES5, functions can only be declared in top-level scope and function scope, not in block-level scope.
  • In ES6, the variable function declared inside the block-level scope behaves like let, that is, it cannot be used outside the block-level scope
 function fun(){<!-- -->
    console.log("I am outside function.")
  }
  if (true) {<!-- -->
    function fun() {<!-- -->
      console.log("I am inside function.");
    }
    fun(); // I am inside function.
  }
  fun(); // I am inside function.
  'use strict' //running result in es6
  function fun(){<!-- -->
    console.log("I am outside function.")
  }
  if (true) {<!-- -->
    function fun() {<!-- -->
      console.log("I am inside function.");
    }
    fun(); // I am inside function.
  }
  fun(); // I am outside function.
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Function extension

[ES6] Destructuring assignment of function parameters

ES6 allows to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called destructuring

You only need to ensure that the data types of the actual parameter and the formal parameter are both arrays or objects, and then you can destructure and assign the function parameters:

function add([x, y]){<!-- -->
  return x + y;
}

add([1, 2]); // 3
function fun({<!-- -->num1:x, num2:y}) {<!-- -->
  return x + y;
}
fun({<!-- -->num1: 1, num2: 2}) // 3

[ES6]Arrow functions

Basic usage

ES6 allows functions to be defined using “arrows” (=>).

var f = v => v;

The arrow function above is equivalent to:

var f = function(v) {<!-- -->
return v;
};
  • If the arrow function does not require parameters, use a () or _ to represent the parameter part.
  • If the arrow function requires multiple parameters, use a () to represent the parameter part.
var f = () => 5;
var f = _ => 5;
// Equivalent to
var f = function () {<!-- --> return 5 };

var sum = (num1, num2) => num1 + num2;
// Equivalent to
var sum = function(num1, num2) {<!-- -->
return num1 + num2;
};

If the code block part of the arrow function is more than one statement, use curly braces to enclose them.

var sum = (num1, num2) => {<!-- -->
    console.log(num2);
    console.log(num1);
return num1 + num2;
}

console.log(sum(1,2)); // 2 1 3

Since curly braces are interpreted as code blocks, if the arrow function directly returns a json, parentheses must be added outside the object.

var person = age => ({<!-- --> name: "Tom", age: age});
console.log(person(21)); //Object {name: "Tom", age: 21}

Arrow functions can be used in conjunction with variable destructuring.

var full = ({<!-- --> name, age}) => name + '-' + age;
console.log(full({<!-- -->name:"Tom",age:21})); // Tom-21

Arrow functions make expressions more concise.

const isEven = n => n % 2 == 0;
const square = n => n * n;

One use of arrow functions is to simplify callback functions.

// normal function writing
var arr1 = [1,2,3].map(function (x) {<!-- -->
return x * x;
});
console.log(arr1); //[1,4,9]

// Arrow function writing
var arr2 = [1,2,3].map(x => x * x);
console.log(arr2); //[1,4,9]

Use attention points

  1. The pointing of this object is variable, but in the arrow function, it is fixed.

    function foo() {<!-- -->
    setTimeout(() => {<!-- -->
      console.log('id:', this.id);
    }, 100);
    setTimeout(function () {<!-- -->
      console.log("id:",this.id);
    },100)
    }
    
    var id = 21;
    foo. call({<!-- --> id: 42 });
    //id: 42
    //id: 21
    
  2. cannot be used as a constructor

  3. Arrow functions have no arguments object

Written at the end

Please continue to pay attention to more JavaScript knowledge and API, please look forward to it. Dear friends, let’s be prepared at all times!

? Originality is not easy, and I hope everyone will support it!
Like it, your recognition is the driving force for my creation!
Collection, your favor is the direction of my efforts!
Comments, your opinion is the wealth of my progress!