JavaScript closures and arrow functions
in Note with 4 comments
JavaScript closures and arrow functions
in Note with 4 comments

closure

Closures are one of the most powerful features in JavaScript

JavaScript allows function nesting

Internal functions can access all variables and functions defined in external functions and all variables and functions accessible by external functions

External functions cannot access variables and functions defined in internal functions

When the life cycle of an internal function is greater than that of an external function, the life cycle of variables and functions defined in the external function will be greater than that of the external function itself because the internal function can access the scope of the external function

When an internal function is accessed by any external function scope in a certain way, a closure And then there is

 var pet = function(name) {   // The outer function defines a variable called "name" var getName = function() { return name;             //  The inner function has access to the "name" variable of the outer function } return getName;            //  Return the inner function, thereby exposing it to outer scopes }, myPet = pet("Vivie"); myPet();                     //  Returns "Vivie"

The following example returns an object containing internal variable methods that can operate on external functions

 var createPet = function(name) { var sex; return { setName: function(newName) { name = newName; }, getName: function() { return name; }, getSex: function() { return sex; }, setSex: function(newSex) { if(typeof newSex == "string"  && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) { sex = newSex; } } } } var pet = createPet("Vivie"); pet.getName();                  //  Vivie pet.setName("Oliver"); pet.setSex("male"); pet.getSex();                   //  male pet.getName();                  //  Oliver

The embedded variables of an embedded function are like the safe of an embedded function. They will keep "stable" -- and safe -- data for embedded functions to run. These embedded functions are not even assigned to a variable, or do not have to have a name.

 var getCode = (function(){ var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify... return function () { return secureCode; }; })(); getCode();    //  Returns the secret code

be careful : If a closed function defines the same variable with the variable name of an external function, the variable can no longer be pointed to in the external function field.

 var createPet = function(name) {  // Outer function defines a variable called "name" return { setName: function(name) {    // Enclosed function also defines a variable called "name" name = name;               // ???  How do we access the "name" defined by the outer function ??? } } }

The magic variable this in the closure is very weird.
You must be very careful when using it, because what this refers to completely depends on where the function is called, not where it is defined.

Use arguments object

The actual parameters of the function will be saved in an array like arguments object. In the function, you can find the arguments passed in as follows:

 arguments[i]

For example, imagine a function to concatenate strings. The only predetermined parameter is the character used to separate the connecting parts in the connected string. This function is defined as follows:

 function myConcat(separator) { var result = "", // initialize list i; // iterate through arguments for (i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; }

You can pass any number of parameters to this function, which will connect each parameter into a string "list":

 // returns "red, orange, blue, " myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; " myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // returns "sage. basil. oregano. pepper. parsley. " myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

be careful

Function Parameters

Two new types of parameters:

Default Parameters

In JavaScript, the default value of function parameters is undefined

 function multiply(a, b) { b = typeof b !== ' undefined' ?   b : 1; return a*b; } multiply(5); //  five

When calling the function, no actual parameter is passed to b, then its value is undefined, so the calculation of a * b results in NaN returned by the function

Remaining parameters

Remaining parameter syntax allows an indefinite number of parameters to be represented as arrays

 function multiply(multiplier, ...theArgs) { return theArgs.map(x => multiplier * x); } var arr = multiply(2, 1, 2, 3); console.log(arr); //  [2, 4, 6]

Arrow function

The arrow function expression (also called fat arrow function) has a shorter syntax than the function expression and lexical binding of this value. Arrow functions are always anonymous.

There are two factors that affect the introduction of the arrow function:

More concise functions

 var a = [ "Hydrogen", "Helium", "Lithium", "Beryl ­ lium" ]; var a2 = a.map(function(s){ return s.length }); var a3 = a.map( s => s.length );

this

Before the arrow function appeared, each new function redefined its own value of this (in strict mode, a new object is undefined in the constructor, and functions called through context objects are called "object methods", etc.)

 function Person() { // The Person() constructor defines `this` as itself. this.age = 0; setInterval(function growUp() { // In nonstrict mode, the growUp() function defines `this`  // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } var p = new Person();

In ECMAScript 3/5, this problem can be fixed by assigning the value of this to a variable

 function Person() { var self = this; //  Some choose `that` instead of `self`.  // Choose one and be consistent. self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); }

In addition, creating a bound function can make this value be correctly passed to the growUp() function

The arrow function captures this value of the closure context, so the following code works normally

 function Person(){ this.age = 0; setInterval(() => { this.age++; // | this| properly refers to the person object }, 1000); } var p = new Person();

Reading materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide

Review method: practice (write code once, run once, test once), Google where you don't understand, read and take notes

Bottom line principle: prefer rewriting once rather than copying and pasting

This review includes: the second part of the function···

Review time: it lasted for several days intermittently... I was drunk too···

Responses
  1. Hi blogger, when you see your blog articles, the technical articles shared are good, and the blog theme is also good.
    Can you add in? I am a website store, a "personal website" publishing platform, which collects many websites of webmasters~~
    http://personal-website.store

    Reply
    1. @Xiaoyan

      To make it simple, Gmail failed to receive the email in the second step.

      Reply
  2. Ask the blogger what the theme is, and can you provide a copy

    Reply
    1. @Guangzhou Linda

      Here you are, https://www.linpx.com/p/lpisme-typecho-theme.html

      Reply