~ 🚀 ㅤ💪 ㅤ Learning Notes, updated for the third time. Modified contents: closure port 🚀 🚀

type

JS has 7 types of data, including basic data type [number (whole tree or floating point), string, Boolean, NULL, undefine, Symbol] and reference type

Symbol

  • The statement

    let s1 = Symbol(a)// Symbol(s1)
    s1
    // Add the DES description to the Symbol variable
    let s2 = Symbol('des')
    // Symbol(s2)
    s2
    // Get the description
    s2.description
    let s3 = Symbol(a);let s4 = Symbol('des');
    // false
    s1 === s3
    // false
    s2 === s4
    Copy the code

    Symbol variables are not strings or objects; each Symbol variable is unique.

  • The prototype

    // Symbol prototype
    Symbol.prototype;
    Copy the code
    1. Symbol {Symbol(symbol.tostringtag): “Symbol”, constructor: ƒ, toString: } *

      1. constructor: ƒ Symbol ()
      2. description: [Exception: TypeError: Symbol.prototype.description requires that ‘this’ be a Symbol at Symbol.get description [as description] () at Symbol.o (: 1:8 3)]
      3. toString: ƒ toString ()
      4. valueOf: ƒ the valueOf ()
      5. Symbol(Symbol.toPrimitive): ƒ Symbol.toPrimitive
      6. Symbol(Symbol.toStringTag): “Symbol”
      7. get description: ƒ description ()
      8. proto: Object
  • conversion

    The Symbol variable does not perform any operations, but can be converted to strings and Booles

    let s = Symbol('des');
    // "Symbol('des')"
    String(s)
    // "Symbol('des')"
    s.toString()
    // true
    Boolean(s);
    Copy the code
  • role

    1. As the object property name

      let obj = {};
      let s = Symbol('des');
      // Attributes can only be created using the [] method, which is a normal string if used with the dot operator
      obj[s] = 1;
      // {Symbol(des):1}
      obj;
      obj.s = 2
      // {Symbol(des):1, s:2}
      obj;
      Copy the code
    2. As a judgment condition variable

      const s1 = Symbol('s1')
      const s2 = Symbol('s2')
      const s3 = Symbol('s3')
      switch(s) {
        case s1:
        case s2:
        case s3:
      }
      Copy the code
  • Gets the Symbol type attribute name

    The Symbol type property can only be obtained by getOwnPropertySymbols and eflect.ownKeys().

    let obj = {a: 1};
    let s1 = Symbol('s1');
    let s2 = symbol('s2');
    obj[s1] = 2;
    obj[s2] = 3;
    // [Symbol(s1),Symbol(s2)]
    Object.getOwnPropertySymbols(obj)
    // ["a", Symbol(s1),Symbol(s2)]
    Reflect.ownKeys(obj)
    Copy the code

String

  • String translation

    For special characters such as \, “, backslash (\) translation is required

    let a = "\ \"
    / / /
    a
    a = "\" "
    // "
    a
    Copy the code

    Or use Unicode notation:

    let a = "\u005c"
    / / /
    a
    Copy the code

    The Unicode notation defaults to only characters between \u0000 and \uFFFF, but {} can be used to change this limitation:

    // only 005c will be translated into \, 1 will not be translated
    let a = "\u005c1"
    / / \ 1
    a
    // translate 005C1 as a whole
    a = "\u{005c1}"
    Copy the code
  • String traversal

    / / you
    let str = String.fromCodePoint(0x2F804);
    for(let i = 0; i < str.length; i++) {
      console.log('str:', str[i]);
    }
    Copy the code

    STR: � STR: �

    for(let s of str) {
      / / you
      console.log('str:', s)
    }
    Copy the code
  • Json format conversion

    // Convert the JS object to a JSON-formatted string
    JSON.stringify({ x: 1.y: 2 })
    // Convert jSON-formatted strings into JS objects
    JSON.parse('{"x":5,"y":6}')
    Copy the code
  • String template

    Using ` ` ` wrapped string, can pass the variables in the string wrote ‘to obtain the value of the variable as part of the string,’ {} to obtain the value of a variable in the ` as part of the string, ` ‘to obtain the value of the variable as part of the string,’ {} ` inside not only support any expression, also support the calling function in it

    let a = 'a';
    function f() {
      return 'f'
    }
    let r = 'I'm a string${a} ${f()}Template `;
    // I am a string f template"
    r
    Copy the code

    The output string reads not only the value of variable A, but also the value returned by function F, with Spaces reserved

  • The label template

    A tag template is not a template, but a way of calling a function. A tag is a function followed by a string template, which is used as an argument to call the function

    // error
    alert 'How are you? '
    // success
    alert 'How are you? `
    Copy the code

    If the following string template has variables, it splits the string into: function (string,… In the form of the value)

    let a = 'I'm fine. '
    let b = 'I'm not well. '
    f 'How are you?${a}How about you?${b} `
    / / is equivalent to
    function f('How are you? '.'what about you? ', a, b);
    Copy the code

variable

  • Scope of a variable

    // All variables are global, except those declared local
    var a;
    if(true) {
      var b = 1;
    }
    / / 1
    b
    // if a is declared in block, it can only be used in block
    let a;
    if(true) {
      let b = 1;
    }
    // error
    b
    Copy the code

    Using let to define variables has the following advantages over var:

    1. Avoid internal variables overwriting external variables of the same name

    2. Avoid leaking loop counters in block-level scopes

      for(var i = 0; i < 10; i++) {}
      / / 10
      i
      for(let j = 0; j < 10; j++) {}
      // error
      j
      Copy the code
  • Promotion of variables

    // undefine
    console.log(a);
    // var defines the a variable to prompt to the beginning of the code
    var a = 1;
    // error
    console.log(b);
    // Let defined variables do not have promotion properties
    let b = 2;
    Copy the code
  • Temporary dead zone

    var a = 1;
    function f() {
      // error
      console.log(a);
      let a = 2;
    }
    Copy the code

    If let is used to declare a in function f, it will bind a to the region, so that global variable A cannot be used. Therefore, an error will be reported if local variable A is used before declaration.

  • Declare variables in block-level scopes

    {
      // error indicates that a has no scope promotion
      a;
      a = 1;
    }
    / / 1
    a
    {
      // undefine
      b;
      var b = 1;
    }
    / / 1
    b
    {
      // error
      c;
      let c = 1
    }
    // error
    c;
    Copy the code

constant

Declare an immutable constant using const.

Note:

  1. Since constants are immutable once declared, declaring a constant without assigning any value is an error

  2. Like the variables declared by let, there is no scope promotion and a temporary dead zone.

  3. For some compound types of data, such as objects with attributes, it is possible to change their attribute values:

    const obj = {a: 1}
    // success
    obj.a = 2
    // error
    obj = {a: 2}
    Copy the code

    A constant is immutable, meaning that the pointer to a constant memory address is immutable, but changing the attributes of the memory address object is not affected, but when obj points to another object, an error is reported.

object

In javascript, an object can be a single entity with attributes and types

Object creation

  • Create objects by object direct quantity

      // Create an object with the name attribute n
      let person = {"name": "n"}
    Copy the code

    Where name is the key name and n is the key value

    The key name can be left unquoted, otherwise it is automatically converted to a string, but an error will result if it does not conform to the basic naming conventions of variables:

    	// error
      let person = {1name: "n"}
      // success
      let person = {"1name": "n"}
    Copy the code
  • Create objects with new

      // Create an empty object with new
      let person = new Object(a)let animal = new Object
      // Use the constructor
      function bird(name) {
        this.name = name;
        this.fly = function() {
          console.log("fly"); }}let myBird = new bird("n");
      myBird.fly();
    Copy the code
  • Create creates an Object with object.create

    // error
    let bird = Object.create()
    // Create a plain empty Object, equivalent to new Object, {}
    let bird = Object.create(Object.prototype);
    // Create an object with the name attribute n
    let bird = Object.create({name:"n"});
    // Create an object that does not inherit from any object, that is, it has no prototype
    let bird = Object.create(null);
    // error
    console.log("bird:", bird.toString());  
    Copy the code

Object reference

let o1 = {p: 1};
// o2 points to o1's memory address
let o2 = o1;
// Change o2's p attribute, in fact, change o1's p attribute value, i.e. O1
o2.p = 2;
// o1 does not change the value of o2, o2 is still: {p:1}
o1 = {p: 2};
Copy the code

This refers to a reference to the current region object:

let o = {p: 1}
o.f = function() {
  / / 1
  this.p;
}
Copy the code

Object properties

Get property values

  • Object.property

      let persion = {
      	name: "n".1: "1"
      }
      persion.name
      // error, the numeric key name can only be obtained as an array
      persion1.
    Copy the code
  • Object[property]

      persion["name"]
    Copy the code

    Object[property] is an associative array, also known as a hash, map, or dictionary. Each Object is an associative array, and the index in parentheses must be quoted, otherwise it will be treated as a variable. Objects map strings to values, whereas arrays map numbers to values

Note:

let p = 1
let persion = {
	p: 2.1:"1"}/ / 2
persion["p"]
// point to the variable p, the result is 1
persion[p]
// 1, without quotation marks, the number is automatically converted to a string
persion[1]
Copy the code

Action attribute

  • The new attribute

    In addition to defining properties at object creation time, you can also add properties dynamically

    // Dynamically add the name attribute
    dog.name = "dog"
    Copy the code
  • Delete the properties

      let dog = {name: "dog"};
      // If the name attribute is deleted, true is returned on success, or if it does not exist
      delete dog.name
    Copy the code

    Delete cannot delete an attribute in an attribute, which can cause memory leaks, such as:

    let dog = {name: {first:"".second:""}}
    let cat.name.first = dog.name.first;
    delete dog.name;
    // fist
    console.log(cat.name.first);
    Copy the code
  • Check the properties

    1. If the object attribute does not exist, undefine is returned

    2. Determine whether an object attribute exists by in

      // Return true if dog has the name attribute
      "name" in dog
      Copy the code
      1. HasProperty is used to determine whether an object has its own properties, that is, non-inherited properties
      // Returns true if the dog object has a name attribute
      dog.hasProperty("name")
      // toString is not the object's own property, so return false
      dog.hasProperty("toString")
      Copy the code
  • Enumerated attribute

      // Cannot determine whether the attribute belongs to the object itself
      for(p in dog) {
        console.log("p:", p);
      }
    Copy the code
  • Modify the properties

      let o1 = {p1: 1.p2: 2};
      o1.p1 = 3;
      o1.p2 = 4
    Copy the code

    You can use the following statement instead:

    let o1 = {p1: 1.p2: 2};
    with(o1) {
      p1 = 3;
      p2 = 4;	
    }
    Copy the code
  • Getter and setter

      let cat = {
        age: 0.get name() {
        	this.age = 10;
        	console.log("get name");
        },
        set name(value) {
        	this.age = 12;
        	console.log("set", value); }};// get name
      cat.name
      / / 10
      cat.age
      // set name
      cat.name = "name";
      / / 12
      cat.age
    Copy the code

Characteristics of attributes

  1. Value/value
  2. Writable, whether the property can be modified
  3. It can be configured without any additional control system
  4. Enumerable [enumerable], whether a property is enumerable
// {value: 1, writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor({ x: 1 }, "x");
Copy the code

Set attribute characteristics:

  • Do not modify the

    let o = {};
    Object.defineProperty(o, "x", {
      value: 1.writable: false.enumerable: true.configurable: true
    });
    o.x = 2;
    // Writability is false, so the value is still 1
    console.log(o.x);
    Object.defineProperty(o, "x", {
      value: 1.writable: true.enumerable: false.configurable: true
    });
    Copy the code
  • An enumeration

    Object.defineProperty(o, "x", {
      value: 1.writable: true.enumerable: false.configurable: true
    });
    o.y = 2;
    // Since x is set to non-enumerable, only y attributes are output
    for (let p in o) {
      console.log(p);
    }
    Copy the code
  • configurable

    Object.defineProperty(o, "x", {
      value: 1.writable: true.enumerable: true.configurable: false
    });
    // error
    Object.defineProperty(o, "x", {
      value: 1.writable: true.enumerable: false.configurable: false
    });
    Copy the code

Object prototype

JS is a programming language based on prototype. Every object has a prototype object, and the prototype object has its own prototype object. This relationship is called prototype chain.

  • inheritance

    function Person() {};
    Person.p1 = 'walk';
    Person.prototype.p2 = 'walk';
    Person.prototype;
    Copy the code
    1. {p: “walk”, constructor: * ƒ} *

      1. p2: “walk”

      2. Constructor: ƒ person ()

        1. p1: “walk”
        2. arguments: null
        3. caller: null
        4. length: 0
        5. name: “person”
        6. prototype: {p: “walk”, constructor: ƒ}
        7. proto: ƒ ()
        8. [[FunctionLocation]]: VM2863:1
        9. [[Scopes]]: Scopes[1]
      3. proto: Object

    let student = new Person();
    student.p = 'study';
    student;
    
    let teacher = new Person();
    teacher.p = 'teach';
    Copy the code
    1. Person {p: “study”}

      1. p: “study”

      2. proto:

        1. p2: “walk”

        2. Constructor: ƒ Person ()

          1. p1: “walk”
          2. arguments: null
          3. caller: null
          4. length: 0
          5. name: “Person”
          6. prototype: {p2: “walk”, constructor: ƒ}
          7. proto: ƒ ()
          8. [[FunctionLocation]]: VM3025:1
          9. [[Scopes]]: Scopes[2]
        3. proto: Object

  • extension

    function Person() {};
    Person.p1 = 'walk';
    Person.prototype.p2 = 'walk';
    let student = new Person();
    student.p = 'study';
    Person.prototype.cry = function(){console.log('cry')}
    // cry
    student.cry();
    student;
    Copy the code
    1. Person {p: “study”}

      1. p: “study”

      2. proto:

        1. cry: ƒ ()

        2. p2: “walk”

        3. Constructor: ƒ Person ()

          1. p1: “walk”
          2. arguments: null
          3. caller: null
          4. length: 0
          5. name: “Person”
          6. prototype: {p2: “walk”, cry: ƒ, constructor: ƒ}
          7. proto: ƒ ()
          8. [[FunctionLocation]]: VM2965:1
          9. [[Scopes]]: Scopes[2]
        4. proto: Object

function

When a function is a property of an object, it is called a method.

Declaration of functions

  • Declarative statements

    function f() {}
    Copy the code
  • Functional expression

    let f = function(p){
      console.log(p);
    };
    // f
    f("f");
    Copy the code
  • The constructor

    let f = new function(r) {
      return r
    }
    // Equivalent to:
    function f(r) {
      return r;
    }
    Copy the code
  • Declare functions in a block-level scope

    In ES5, it is allowed to declare a function in a block-level scope, which can be called outside the scope due to function promotion:

    function f() {
      console.log('outside')}; (function() {
      if(true) {
    		function f() {
         console.log('inside'); }}// insidef(); }) ()Copy the code
  • Function declaration statement promotion

    f();
    // the f function declaration is promoted before the call
    function f() {};
    Copy the code

    But function expressions cannot be promoted:

    // error
    f();
    let f = function() {};
    Copy the code
  • Get the number of parameters

    function f(a, b) {}
    / / 2
    f.length
    Copy the code
  • Get function name

    function f() {}
    // f
    f.name
    let f1 = function f2() {}
    // f2
    f1.name
    Copy the code
  • The eval command

    The function of this command is to execute a string as a statement. Variables declared by eval in strict mode have no external impact.

    eval('let a = 1');
    // error
    a;
    Copy the code

Function call

  • A function expression that executes immediately

    Function expressions that execute immediately with () are called function expressions that execute immediately (IIFE)

    // Call f immediately
    (function f(() {}) ()
    Copy the code

    The above f function is wrapped with (), because js interprets function as a statement by default. If () is not added, the following error is reported:

    VM3801:1 Uncaught SyntaxError: Unexpected token ‘)’

    / / statements
    function f1() {};
    / / expression
    let f = f2() {};
    Copy the code

    Functions: 1. Avoid polluting global variables; 2. Create private variables that cannot be accessed externally

    // Avoid polluting global variables
    var a = 1;
    (function() {
      var a = 2;
      / / 2a; }) ()/ / 1
    a;
    
    // After some logical operations, the result is assigned to r
    let r = (function() {
      let a = 1;
      let b = 2;
      return a + b;
    })
    / / 3
    r;
    Copy the code

Note:

Function definitions are invalid in conditional statements, but still do not return an error:

if (true) {
  function f1(){}}// F1 can be called outside the if statement because the function goes up
f1()
Copy the code

Parameters of a function

  • Parameters are omitted

    The arguments in the function have no relation to the arguments actually passed in

    function f(a, b){}
    f(1.2.3.4);
    / / 2
    f.length
    Copy the code

    The arguments object, however, gets the values of the arguments passed in:

    function f(a, b){
      console.log(arguments[0]);
      console.log(arguments[1]);
      console.log(arguments[2]);
    }
    / / 1 2 3
    f(1.2.3.4);
    Copy the code

    In normal mode, you can modify the following parameters:

    function f(a, b){
      arguments[0] = 2;
      arguments[1] = 3;
      return a + b;
    }
    // Return 5 instead of 3
    f(1.2.3.4);
    Copy the code

    However, in strict mode, modifying parameters has no effect.

  • Parameters of the same name

    If there is an argument with the same name, take whatever the value of the last argument is

    function f(a, a) {
      return a;
    }
    // undefine
    f(1, undefine);
    Copy the code
  • The default parameters

    function f(a, b = 1) { 
      return a + b
    }
    / / 2
    f(1);
    Copy the code
  • The remaining parameters

    function f(a, ... b) {
      return b;
    }
    / / [2, 3, 4]
    f3(1.2.3.4);
    Copy the code

Method of function

closure

The concept of closures

Closures are functions that can access variables outside the scope.

When unable to access a function scope, can often be created within the function to access another function, based on the characteristics of the scope chain is the function can access to the upper variables, now just need to create internal function as the return value is returned, can let the external scope access to functions within the scope of variables.

function f1() {
    let a = 1;
    function f2() {
        console.log('a:', a);
    }
    return f2;
}
let f3 = f1();       / / 1
Copy the code

The inner function (f2) created in function scope is a closure.

The role of closures

  1. Gets the variables of the inner function

    function f1() {
      // Visible to F2
      let p1 = "p1";
      function f2() {
        // Not visible to F1, visible to F3
        let p2 = "p2";
        console.log(p1)
        function f3() {
          // p2
          console.log(p2); }}return f2;
    }
    let f4 = f1();
    // p1
    f4();
    Copy the code

    Although p1 does not operate outside of function f1, function F4 still returns the value of p1 in function F1 via function f2.

  2. Save the variables of the inner function

    let add;
    function f1() {
      let n = 0
      add = function () {
        n = n + 1;
      }
      function f2() {
        console.log(n)
      }
      return f2;
    }
    let f3 = f1();
    / / 0
    f3();
    add();
    / / 1
    f3();
    Copy the code

    It can be seen from the above results that the value of n variable is not destroyed and recycled after f3 function call, but is saved, because F2 is assigned to the global variable F3, that is, F3 holds F2, and F2 carries f1 reference, so it is not recycled.

  3. Avoid global contamination

    Variables in a function scope cannot be accessed elsewhere to avoid string modification.

  4. Modular programming

    const obj = (function () {
      let name = 'xiaoli';
      return {
        getName: function () {
          return name;
        },
        setName: function (value) { name = value; }}; } ()); obj.name; obj.getName(); obj.setName('xiaohuang');
    Copy the code

    The above code will get and set the name variable into a separate module, just need to access the obJ object method to operate on the name variable is simple and clear.