1. Process oriented vs. object oriented

1.1 Process-oriented

Fried rice with egg

  • Process oriented is to analyze the steps needed to solve the problem, and then use the functions to achieve these steps step by step, when using the time and then one by one call can be.

1.2 Object-oriented

1:1.2

  • Object orientation is to decompose the transaction into objects, and then divide and cooperate among objects.
  • Thinking characteristics
    • Encapsulate the common properties and behaviors of extracted objects into a class (template)
    • Instantiate the class and get the object of the class

1.2.1 features

  • encapsulation

    • Each object exists on its own, with its own properties and methods that must be invoked. This ensures the security of properties and methods inside the object
  • inheritance

    • Subclasses can inherit properties and methods from their parent class through the extends keyword. Reduce the redundancy of the code, omit a lot of duplicate code.
  • polymorphism

    • Subclasses can define their own methods internally, or they can override methods of their parent class. Extends the applicability and flexibility of classes.

1.3 Comparison between process orientation and object orientation

Process oriented object-oriented
advantages Performance is higher than object-oriented, suitable for hardware is closely related to things, such as single-chip microcomputer on the use of process-oriented programming. Easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain
disadvantages Not easy to maintain, reuse, and expand Performance is lower than process-oriented
  • Process oriented is to analyze the steps needed to solve the problem, and then use the function to achieve these steps step by step, when using one by one can call;

    • Advantages: easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, easier to maintain.
    • Disadvantages: Performance is better than process-oriented.
  • Object orientation is to decompose the transaction which constitutes the problem into various objects, and then divide the work and cooperate among the objects. The object is not built to complete a step, but to describe the behavior of something in the whole problem-solving step.

    • Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, high overhead, more resource consumption. For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor.
    • Disadvantages: No object-oriented easy maintenance, easy reuse, easy to expand.

2. Objects and classes

2.1 object

An object is made up of properties and methods: an unordered collection of key-value pairs, referring to a concrete thing

  • 2. A characteristic of a thing, represented by an attribute in an object (commonly used noun).
  • 2. The act of something expressed by means in an object (often a verb).

2.1.1 Creating objects

// The following code is a review of objects
// the literal creates the object
var ldh = {
    name: 'Andy Lau'.age: 18
}
console.log(ldh);// {name:'ldh', age:18}

The constructor creates the object
function Star(name, age) {
    this.name = name;
    this.age = age;
 }
//
var ldh = new Star('Andy Lau'.18)// instantiate the object
console.log(ldh);// Star {name:' Andy ', age: 18}
Copy the code

2.2 class

The new concept of classes in ES6 allows you to declare a class using the class keyword and then instantiate objects from that class. A class abstracts the common part of an object. It refers to a general class. An object refers to a particular class

The class is the drawing, and the object instance is the house built according to the drawing

  • Variables are containers for data
  • An array is a container for a group of data
  • Methods (functions) are containers for code
  • Objects are super containers (data, arrays, methods, objects)
  • Classes classify objects. During the classification process, some common features of objects are extracted and described by classes

2.2.1 create classes

 Create a star class
 class Star {
   // Put the class's common attributes inside constructor
   constructor(name, age) {
   this.name = name;
   this.age = age; }}// 2. Use class to create object new
   var ldh = new Star('Andy Lau'.18);
   console.log(ldh);// Star {name:' Andy ', age:18}
Copy the code

From the results, we can see that we run the results the same way we used the constructor

2.2.2 Class Creation Add attributes and methods

 // 1. Create a class
class Star {
    Constructor is a constructor or constructor
    constructor(uname, age) {
      this.uname = uname;
      this.age = age;
    }/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > note that don't need to add a comma between method and the method
    sing(song) {
      console.log(this.uname + 'sing'+ song); }}// 2. Use class to create object new
var ldh = new Star('Andy Lau'.18);
console.log(ldh); // Star {uname: "Andy lau ", age: 18}
ldh.sing('freezing rain'); // Andy Lau sings Ice Rain
Copy the code

Note:

  1. The class keyword is used to create classes with names that we have traditionally definedUppercase
  2. Class contains a constructor function that accepts arguments passed in and returns an instance object
  3. Whenever new generates an instance, the constructor function willAutomatically callThis function, if we don’t write this function, the class will automatically generate this function
  4. Between multiple function methodsYou don't need to add a commaseparated
  5. An instanceNew cannot be omitted
  6. Syntax specification, create class name without parentheses, generate instance class name with parentheses, constructors do not need function
  7. Class is not promoted, so needsFirst define, then instantiate

Step to create an object using new

  1. Allocates a free space in memory to store the new object
  2. Point this to the current object
  3. Performs functions to set object properties and method values
  4. Return this to the address of the object (so there is no return in the constructor)

2.2.3 Differences and similarities between constructors and classes

The difference between

  • Every time an instance is created, the sayName function is recreated, which takes some performance to run

  • Class functions are built on Prototype, and syaName methods on each instance point to the same address, i.e., the same method, which has improved performance over constructors.

   function Person(name) {
      this.name = name
      this.sayName = function() {
        console.log(this.name)
      }
    }
    const p1 = new Person('kaoso')
    const p2 = new Person('kaoso')
    p1.sayName() / / kaoso
    p2.sayName() / / kaoso
    console.log(p1.sayName === p2.sayName) //false
    console.log(Person.prototype)
    /* * {constructor: ƒ} * constructor: ƒ Person(name) * __proto__: Object * * */
Copy the code
   class Student {
      constructor(name) {
        this.name = name
      }
      sayName() {
        console.log(this.name)
      }
    }
    const p3 = new Student('McNuggets')
    const p4 = new Student('McNuggets')
    p3.sayName() / / McNuggets
    p4.sayName() / / McNuggets
    console.log(p3.sayName === p4.sayName) // true
    console.log(Student.prototype)
    /* *{constructor: ƒ, sayName: ƒ} constructor: ƒ Student(name), sayName: ƒ sayName(), __proto__: Object */
Copy the code

similarity

  • This refers to instances
  function Person(name) {
      this.name = name
      this.sayName = function() {
        console.log(this)}this.sayHello = function() {
        const check = this.sayName
        check()
      }
    }
    const p1 = new Person('kaoso')
    const p2 = new Person('McNuggets')
    p1.sayName() // Person {name: "高秀", sayName: ƒ, sayHello: ƒ}
    p2.sayName() // Person {name: "麦乐", sayName: ƒ, sayHello: ƒ}
    p1.sayHello() // undefiend
Copy the code
  class Student {
      constructor(name) {
        this.name = name
      }
      sayName() {
        console.log(this)}sayHello() {
        const checkThis = this.sayName
        checkThis()
      }
      sayBind() {
        const checkThisBind = this.sayName.bind(this)
        checkThisBind()
      }
    }
    const p5 = new Student('chapter three')
    const p6 = new Student('history')
    p5.sayName() // Student {name: ""}
    p6.sayName() // Student {name: "history "}
    p5.sayHello() // Undefiend
    p5.sayBind() // Student {name: ""}
Copy the code

2.2.4 Class inheritance

  1. Subclasses use the super keyword to access methods of their parent class
// the super keyword calls the superclass ordinary function
class Father {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    sum() {
        console.log(this.x + this.y);
    }
    say() {
        return 'I am the father'; }}class Son extends Father {
    constructor(x, y) {
        super(x, y); // The constructor in the parent class is called with super
    }
    say() {
        // console.log(' I am the son ');
        console.log(super.say() + '的儿子');
        // super.say() calls the ordinary say() function in the superclass.}}var son = new Son(1.2);
son.sum(); // The result is 3
son.say(); // I am my father's son
Copy the code
  • Note:

    • In inheritance, if you instantiate a subclass to output a method, see if the subclass has the method, and execute the subclass’s method first

    • In inheritance, if there is no method in the subclass, look for the method in the parent class, if there is, execute the method in the parent class (nearest principle).

    • If a subclass wants to inherit the methods of its parent class while extending its own methods internally, it calls the constructor of the parent class with super, which must be called before the subclass this

  1. A subclass inherits its parent method while extending its own method
// The superclass has addition methods
class Father {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    sum() {
        console.log(this.x + this.y); }}// Subclasses inherit superclass addition methods and extend subtraction methods
class Son extends Father {
    constructor(x, y, z) {
        // Call the parent constructor with super
        // super must be called before subclass this
        super(x, y);
        this.z = z;
    }
    subtract() {
        console.log(this.x - this.y - this.z); }}var son = new Son(5.3.9);
son.subtract(); / / - 7
son.sum(); / / 8
Copy the code
  1. Always be aware of the orientation of this. Use this for all common attributes and methods in the class

    1. This in constructor refers to the instance object generated from new
    2. Custom methods also refer to instances of new objects
    3. After the event is bound, this points to the event source that triggered the event
var that;
var _that;
class Star {
    constructor(uname, age) {
        // This in constructor points to the created instance object
        that = this;
        console.log(this);

        this.uname = uname;
        this.age = age;
        this.btn = document.querySelector('button');
        // this. Sing's this refers to BTN
        this.btn.onclick = this.sing;
    }
    sing() {
        // This in the sing method refers to the BTN button because it calls the function
        console.log(this);

        console.log(that.uname); // That stores this from constructor
    }
    dance() {
        // This in this dance refers to the instance object LDH because LDH calls this function
        _that = this;
        console.log(this); }}var ldh = new Star('Andy Lau');
console.log(that === ldh); // true
ldh.dance();
console.log(_that === ldh); // true
Copy the code
  1. In ES6 there is no class variable promotion, so you must define a class before you can instantiate an object from that class!

3. Switch the TAB bar of the object-oriented version

3.1 Functional Requirements

  1. Click the TAB bar to switch effects.
  2. Click the + sign to add TAB items and content items.
  3. Click x to delete the current TAB and content items.
  4. Double-click TAB text or content text to modify the text content inside

3.2 Case Preparation

  1. Gets the title element
  2. Get the content element
  3. Get delete small button X number
  4. Create js file, define class, add required attribute methods (toggle, Delete, add, modify)
  5. Always pay attention to the orientation of this

3.3 switch

  • Bind click events for the captured title, display the corresponding content area, and store the corresponding index

     this.lis[i].index = i;
     this.lis[i].onclick = this.toggleTab;
    Copy the code
  • Use exclusivity to achieve a display of only one element

     toggleTab() {
       // Remove all title and content class styles
         for (var i = 0; i < this.lis.length; i++) {
         this.lis[i].className = ' ';
         this.sections[i].className = ' ';
         }
       // Add an activation style for the current title
         this.className = 'liactive';
        // Add an activation style for the current content
         that.sections[this.index].className = 'conactive';
      }
    Copy the code

3.4 add

  • Add button + bind click event

     this.add.onclick = this.addTab;
    Copy the code
  • Realize the title and content of the addition, do a good job of exclusive processing

    addTab() {
        that.clearClass();
        // (1) Create the li element and section element
        var random = Math.random();
        var li =   
             ;
        var section = '
            
    Test '
    + random + '</section>'; // (2) append the two elements to the corresponding parent element that.ul.insertAdjacentHTML('beforeend', li); that.fsection.insertAdjacentHTML('beforeend', section); that.init(); } Copy the code

3.5 delete

  • Bind the click event to the element’s delete button X

     this.remove[i].onclick = this.removeTab;
    Copy the code
  • Get all of the parent element of the click delete button, delete the corresponding title and content

     removeTab(e) {
         e.stopPropagation(); // Prevent bubbling prevents li from triggering the toggle click event
         var index = this.parentNode.index;
         console.log(index);
         // The corresponding li and section remove() methods can remove the specified element directly
         that.lis[index].remove();
         that.sections[index].remove();
         that.init();
         / / when we delete not selected li, the original https://github.com/sl1673495/leetcode-javascript/issues/11 to selected li stays the same
         if (document.querySelector('.liactive')) return;
         // When we delete the selected li, let the previous Li be selected
         index--;
         // Manually calling our click event does not require a mouse trigger
         that.lis[index] && that.lis[index].click();
     }
    Copy the code

3.6 the editor

  • Double-click to disallow the selected text
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
Copy the code
  • Make the text box select automatically
// Make the text box automatically selected
input.select();
Copy the code
  • Bind double click events to elements (title and content)

     this.spans[i].ondblclick = this.editTab;
     this.sections[i].ondblclick = this.editTab;
    Copy the code
  • In the double-click event processing text selected state, modify the internal DOM node, to achieve the transfer of new and old value values

    editTab() {
        var str = this.innerHTML;
        // Double-click to disallow the selected text
        window.getSelection ? window.getSelection().removeAllRanges() : 				    document.selection.empty();
        // alert(11);
          this.innerHTML = '<input type="text" />';
          var input = this.children[0];
          input.value = str;
          input.select(); // The text inside the text box is selected
          // When we leave the textbox we give the value inside the textbox to span
          input.onblur = function() {
          this.parentNode.innerHTML = this.value;
          };
          // Press Enter to assign the values in the text box to span
          input.onkeyup = function(e) {
          if (e.keyCode === 13) {
          // Manually calling the form out-of-focus event does not require a mouse-off operation
          this.blur(); }}}Copy the code

Constructors and prototypes

4.1 Three ways to create objects — review

  1. Literal mode

    var obj = {};
    Copy the code
  2. The new keyword

    var obj = new Object(a);Copy the code
  3. Constructor mode

    function Person(name,age){
      this.name = name;
      this.age = age;
    }
    var obj = new Person('zs'.12);
    Copy the code

4.2 Static members and Instance Members

  • Instance members are members added by this inside the constructor, as in uname age sing. Instance members can only be accessed by the instantiated object

  • Static members A member added to the constructor itself, as in the following code, is a static member, which can only be accessed through the constructor

function Star(uname, age) {
     this.uname = uname;
     this.age = age;
     this.sing = function() {
     console.log('I can sing');
    }
}
Star.sex = 'male';
var ldh = new Star('Andy Lau'.18);
console.log(ldh.uname);// Instance members can only be accessed through the instantiated object
console.log(Star.sex);// Static members can only be accessed through constructors
Copy the code

The constructor method is nice, but it can be a waste of memory.

4.3 Prototype Object prototype and object prototype __proto__

4.3.1 Prototype objects

Each constructor has a Prototype property that points to another object.

Note that prototype is an object whose properties and methods are all owned by the constructor.

Define those immutable methods directly on a Prototype object so that all object instances can share them. / / true. You can save the opening of memory space

Star.prototype.sing = function() {
	console.log('I can sing');
}
var ldh = new Star('Andy Lau'.18);
var zxy = new Star('Jacky Cheung'.19);
console.log(ldh.sing === zxy.sing);// true
Copy the code

4.3.2 Object prototype

Object will have a __proto__ attribute pointing to the constructor’s Prototype object

The prototype constructor allows us to use the properties and methods of the prototype object because the object has a __proto__ prototype.

__proto__ object prototype is equivalent to prototype object prototype ldh._proto_=== star.prototype; // true

The __proto__ object prototype is meant to provide a direction, or a route, for object look-up mechanisms, but it is a nonstandard property and therefore cannot be used in actual development. It only points internally to the prototype object

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
Star.prototype.sing = function () {
    console.log('I can sing');
}
var ldh = new Star('Andy Lau'.18);
ldh.sing();
Copy the code

The constructor function

Both __proto__ and prototype objects have a constructor property inside. Constructor we call it a constructor because it refers back to the constructor itself.

Constructor is used primarily to record which constructor the object refers to, and it can redirect the prototype object to the original constructor.

In general, object methods are set in the constructor’s prototype object, Prototype. If we have methods for more than one object, we can assign to the prototype object as an object, but this overwrites the original contents of the constructor prototype object so that the modified constructor object no longer points to the current constructor. At this point, we can add a constructor pointing to the original constructor in the modified prototype object.

function Star(uname, age) {
     this.uname = uname;
     this.age = age;
}
In many cases, we need to manually refer back to the original constructor using the constructor property
Star.prototype = {
// If we modify the original stereotype object and assign the stereotype object to an object, we must manually use constructor to refer back to the original constructor
   constructor: Star, // Manual setting refers back to the original constructor
   sing: function() {
     console.log('I can sing');
   },
   movie: function() {
     console.log('I'll be in a movie.'); }}var zxy = new Star('Jacky Cheung'.19);
console.log(Star.prototype);

zxy.constructor = zxy.__proto__.constructor = Star.prototype = Star;
Copy the code

Set the constructor property as shown below:

If the constructor property is not set, as shown:

4.4.1 Function of constructor

Is the prototype for the instance constructor object exposed, for example, if you write a plug-in, others get you instantiated object, if someone want to extend the objects, you can use the instance. The constructor. The prototype to modify or extend the prototype object.

var a,b;
(function(){
  function A (arg1,arg2) {
    this.a = 1;
    this.b=2; 
  }

  A.prototype.log = function () {
    console.log(this.a);
  }
  a = new A();
  b = new A();
})()
a.log();/ / 1
b.log();/ / 1

// We can't access A directly because A is in A closure
// So add methods to a.protoType using constructor
a.constructor.prototype.log2 = function () {
  console.log(this.b)
}

a.log2();/ / 2
b.log2();/ / 2
Copy the code

4.5 prototype chain

Each instance object in turn has a __proto__ attribute, pointing to the constructor’s prototype object, which is also an object and has a __proto__ attribute, so that layer by layer the prototype chain is formed.

4.5.1 Member Search Mechanism

  1. When accessing properties (including methods) of an object, you first look up whether the object itself has the properties.
  2. If not, look for its prototype (that is, the prototype object __proto__ points to).
  3. If not, find the prototype of the prototype Object (Object’s prototype Object).

. And so on until Object is found (null).

// Object is a built-in Object. You can only add methods to it
Object.prototype.sing1 = function() {
    console.log('I can act.');
}
Object.prototype.uname1 = 'Hello.';

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
Star.prototype.sing = function() {
    console.log('I can sing');
}
var ldh = new Star('Andy Lau'.18);
console.log(ldh.uname1);
console.log(ldh.__proto__);
// 1. Any object has a __proto__ prototype, pointing to the prototype object
console.log(Star.prototype);
console.log(Star.prototype.__proto__);
// 2. The __proto__ prototype in our Star prototype Object points to Object.prototype
console.log(Object.prototype.__proto__);
// the __proto__ prototype pointer is null
Copy the code

4.6 Trigonometric relationship between constructor instance and prototype object

4.7 This points to in the prototype object

This in the constructor and this in the prototype object refer to our new instance object

4.8 Built-in methods for array extension through prototypes

Note: Built-in objects cannot override their prototype object as objects, only through. To append methods.

 Array.prototype.sum = function() {
   var sum = 0;
   for (var i = 0; i < this.length; i++) {
   sum += this[i];
   }
   return sum;
 };
 // The sum() method already exists in the array object and can be used to sum the data
Copy the code

5. Extends Call (ES6 extends)

  • Call () can call functions
  • Call () can modify the reference to this. When call() is used, the first parameter is this, and the second parameter is 3. Use commas to separate connections

5.1 Inheritance Attributes

 // 1. Parent constructor
 function Father(uname, age) {
   // This points to an object instance of the parent constructor
   this.uname = uname;
   this.age = age;
 }
  // 2. Child constructor
function Son(uname, age, score) {
  // This points to an object instance of the child constructor
  3.Father.call();this, uname, age);
  this.score = score;
}
var son = new Son('Andy Lau'.18.100);
console.log(son);
Copy the code

5.2 Borrow archetypal object inheritance methods

Key point: The instance object created with new Father() is also a method that can be called on the Father prototype object

// 1. Parent constructor
function Father(uname, age) {
  // This points to an object instance of the parent constructor
  this.uname = uname;
  this.age = age;
}
Father.prototype.money = function() {
  console.log(100000);
 };
// 2. Child constructor
function Son(uname, age, score) {
      // This points to an object instance of the child constructor
      Father.call(this, uname, age);
      this.score = score;
}
  
// Son.prototype = Father.prototype; This is problematic because if you change the child, the parent will change as well
// New Father() is the created instance object, which is also a method on the Father prototype object that can be called
Son.prototype = new Father();
If you modify a prototype object in the form of an object, remember to use constructor to refer back to the original constructor
Son.prototype.constructor = Son;

// This is a subconstructor specific method
Son.prototype.exam = function() {
    console.log('Kids have tests');

}
var son = new Son('Andy Lau'.18.100);
console.log(son);
Copy the code

6. New methods in ES5

6.1 Array method forEach traverses a number group

# in forEachreturnDoes not terminate iteration arr. ForEach (function(value, index, array) {
       // The first argument is an array element
       // The second argument is the index of the array element
       // The third argument is: the current array
 })
  // The for loop equivalent to array traversal has no return value
Copy the code

ForEach () does not provide a syntax for exiting the entire loop

Solution: Throw exceptions and catch exceptions

let arr=['a'.'b'.'c'.'d']
try{
    arr.forEach((ele,i) = >{
    if(i==1) {// Throw an exception
        throw new Error(' ')}console.log(ele,i);
    })
// Exception catch
}catch(e){
}
Copy the code

6.2 Array Method filter Filters arrays

  var arr = [12.66.4.88.3.7];
  var newArr = arr.filter(function(value, index,array) {
  	 // The first argument is an array element
     // The second argument is the index of the array element
     // The third argument is: the current array
     return value >= 20;
  });
  console.log(newArr);//[66,88] // The return value is a new array
Copy the code

6.3 Array method some

# met in somereturn trueUse some, some to find if there are any elements in the array that meet the criteriavar arr = [10.30.4];
 var flag = arr.some(function(value,index,array) {
     // The first argument is an array element
     // The second argument is the index of the array element
     // The third argument is: the current array
     return value < 3;
  });
console.log(flag);//false returns a Boolean value that terminates the loop as soon as one element is found
Copy the code

6.4 Some and forEach

  • If you are looking for a unique element in an array, use some. If you return true in some, it is more efficient to terminate the iteration
  • A return does not terminate an iteration in forEach

6.5 Obtaining the Attribute Name of an Object

Keys Gets the name of the property in the current Object and returns an array

 var obj = {
     id: 1.pname: 'millet'.price: 1999.num: 2000
};
var result = Object.keys(obj)
console.log(result)/ / / id, pname, price, num
Copy the code

6.6 Object. DefineProperty

Object.defineproperty Sets or modifies attributes in an Object

Object.defineProperty(Object, modified or new attribute name, {value: The value of the modified or added attribute,writable:true/false.// It is not allowed to change the value of this property if the value is false. The default value is true
    enumerable: false.// Enumerable is not allowed if it is false
    configurable: false  // If the configured information is false, no deletion of this property is allowed. The property can be deleted or modified again
})	
Copy the code

7. Function definition and call

7.1 How to define functions

1.way1Function declarationfunctionKeyword (Naming functions)
function fn(){} 2. Mode 2 function expression (Anonymous functions)
var fn = function(){} 3. Method 3new Function(-------- not recommendedvar f = new Function('a'.'b'.'console.log(a + b)');
f(1.2);

var fn = new Function(Parameters' 1 '.Parameters' 2 '. .'Function body'Note,All functions are instances of Function (objects). Functions also belong to objects */
Copy the code

7.2 Function Invocation

/* 1. The normal function */
function fn() {
	console.log('Peak of my life');
}
fn(); 

/* 2. Object method */
var o = {
  sayHi: function() {
  	console.log('Peak of my life');
  }
}
o.sayHi();

/* 3. Constructor */
function Star() {};
new Star();

/* 4. Bind event function */
 btn.onclick = function() {};   // To call this function, click the button
 
/* 5. Timer function */
setInterval(function() {}, 1000); This function is timer automatic1Call once per second/* 6. Execute the function immediately (self-calling the function)*/
(function() {
	console.log('Peak of my life'); }) ();Copy the code

8. this

8.1 The this pointer inside the function

Generally pointing to our caller.

8.2 Change the this pointer inside the function

8.2.1 call method

The call() method calls an object. This is simply the way a function is called, but it can change the this direction of the function.

The first argument is the object to which this points, and the passing arguments are separated by commas

Application scenario: Often perform inheritance.

var o = {
	name: 'andy'
}
 function fn(a, b) {
      console.log(this);
      console.log(a+b)
};
fn(1.2)// This refers to window and the result is 3
fn.call(o,1.2)// This refers to the object o, separated by a comma, and the result is 3
Copy the code

8.2.2 apply method

The apply() method calls a function. This is simply the way a function is called, but it can change the this direction of the function.

The first argument is the object to which this points, passed in an array

Application scenario: Often associated with arrays

For example, we can use Apply to maximize arrays with the help of mathematical built-in objects
// Math.max
var arr = [1.66.3.99.4];

// var max = Math.max.apply(null, arr);
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);

Math.max(... arr)// ES6
Copy the code

8.2.3 bind method

The bind() method does not call a function, but it does change the this pointer inside the function and returns any new function that was created after the original function changed this

You can use bind if you just want to change this and don’t want to call the function

Application scenario: Do not call the function, but still want to change the this reference

// We have a button. When we click it, we disable it. After 3 seconds, we turn it on
function fn1() {
    this.disabled = false;
}
var btns = document.querySelectorAll('button');
for (var i = 0; i < btns.length; i++) {
    btns[i].onclick = function() {
        this.disabled = true;
        // Because the function inside the timer refers to the window object
        setTimeout(fn1.bind(this), 2000); }}Copy the code

8.2.4 Similarities and Differences of Call, apply and bind

  • Common: Both can change the “this” direction

  • Difference:

    • Call and Apply call the function and change the this reference inside the function.
    • Call and Apply pass different parameters, which are separated by commas, and apply pass in arrays
    • Bind does not call a function; it can change the this pointer inside a function.
  • Application scenarios

    1. Call often does inheritance.
    2. Apply is often associated with arrays. For example, using mathematical objects to realize the maximum and minimum values of arrays
    3. Bind does not call the function, but also wants to change the this pointer. For example, change the this pointer inside the timer.

Note: If call, apply, or bind receives null or undefined as the first argument, this argument will be ignored.

function foo () {
  console.log(this.a)
}
var a = 2
foo.call()
foo.call(null)
foo.call(undefined) output:2
2
2
Copy the code

9. Strict mode

Strict mode requirements reference

9.1 Enabling strict Mode

  1. Turn on strict mode for the script
(function (){
  // The strict mode is enabled in the current self-calling function, and the normal mode remains outside the current function
"use strict";
       var num = 10;function fn() {}
})();
/ / or
<script>(Not recommended)"use strict"; // The current script tag turns strict mode on
</script>
<script>
  			// The current script tag is not in strict mode
</script>
Copy the code
  1. Turn on strict mode for functions (recommended for code merging)
function fn(){
    // The declaration precedes all statements in the function body
"use strict";return "123";
} 
// The fn function is in strict mode
Copy the code

9.2 Changes in Strict Mode

  • This is undefined in strictly global scoped functions
  • In strict mode, timer This still points to window

10. Higher-order functions

Higher-order functions are functions that operate on other functions, taking functions as arguments or output functions as return values.

  • A function is also a data type that can also be passed as an argument to another argument. The most typical is as a callback function.

  • A function can also be passed back as a return value

11. The closure

11.1 The concept of closures

A closure is a function that has access to variables in the scope of another function. Simply put, a scope can access local variables inside another function.

The essence of the closure’s parent function’s scoped object (not destroyed)

The function of the variable is the closure function.

  • Scope: Is an object used to hold data

  • When a function is called, a temporary scoped object is created to hold local variables and parameters, which is destroyed once the local call ends.

    • Two scoped objects are generated when the same function is called twice
    • Since the child function uses a local variable of the parent function, the resulting scoped object cannot be destroyed after the parent function is executed (nor will the local variable of the parent function be destroyed after the function is called).
// Closure: our fun scope accesses the local variable num in another function, fn
// fn is the closure function
function fn() {
    var num = 10;

    function fun() {
        console.log(num); / / 10

    }
    return fun;
}
let f= fn();
f();
Copy the code

11.2 The role of closures

Extend the scope of a variable.

The local variable num is accessed through f() in the global scope outsidefunction fn() {
    var num = 10;
    function fun() {
        console.log(num);
    }
    return fun;
    
    // return function () {
    // num++;
    // console.log(num);
    // }
 }
var f = fn();
/ / similar to
// var f = function() {
// console.log(num);
/ /}
f();
Copy the code

11.3 Closure Application

  1. Click li to print the current LI index
// 1. We can add attributes dynamically
var lis = document.querySelector('.nav').querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].index = i;
    lis[i].onclick = function() {
        // console.log(i);
        console.log(this.index); }}// 2. Use the closure method to get the current li index
for (var i = 0; i < lis.length; i++) {
    // Use the for loop to create four immediately executed functions
    // Immediately executing functions also become small closures
    // Because any function that executes immediately can use its I variable
    (function(i) {
        lis[i].onclick = function() {
            console.log(i)
        }
    })(i)
}

// 3. Use the block-level scope of let
var lis = document.querySelector('.nav').querySelectorAll('li');
for (let i = 0; i < lis.length; i++) {
    lis[i].onclick = function() {
        console.log(i); }}Copy the code
  1. After 3 seconds, print the contents of all li elements (also three ways)
 for (var i = 0; i < lis.length; i++) {
   (function(i) {
     setTimeout(function() {
     console.log(lis[i].innerHTML);
     }, 3000)
   })(i);
}

// Add: print one every 3 seconds
 for (var i = 0; i < lis.length; i++) {
   (function(i) {
     setTimeout(function() {
     console.log(lis[i].innerHTML);
     }, 3000*i)
   })(i);
}
Copy the code
  1. Calculate the price of a taxi
/* Demand analysis Taxi fare starts at 13(within 3 kilometers) and increases by 5 yuan for each additional kilometer. Users input the mileage to calculate the price of the taxi. If there is congestion, an extra 10 yuan will be charged for the total price */

 var car = (function() {
     var start = 13; // Start price local variable
     var total = 0; // Total price local variable
     return {
       // Normal total price
       price: function(n) {
         if (n <= 3) {
           total = start;
         } else {
           total = start + (n - 3) * 5
         }
         return total;
       },
       // The cost after congestion
       yd: function(flag) {
         return flag ? total + 10: total; }}}) ();console.log(car.price(5)); / / 23
console.log(car.yd(true)); / / 33
Copy the code
  1. This points to the
var name = "The Window";
var object = {
	name: "My Object".getNameFunc: function() {
			// This of the anonymous function refers to window
			return function() {
					return this.name; }; }};console.log(object.getNameFunc()());// The Window
/ / similar to
var f = object.getNameFunc();
var f = function() {
    return this.name;
}
f();
// No closure is generated because there are no local variables
-----------------------------------------------------------------------------------
var name = "The Window";varobject = {name: "My Object".getNameFunc: function() {
      	// Objec calls this function. This refers to obj
    		var that = this;
    		return function() {
    				returnthat.name; }; }};console.log(object.getNameFunc()());// My Object
// A closure is generated because that is a local variable
Copy the code

12. Recursion

12.1 What is recursion

A function is recursive if it can call itself internally. Simple to understand: a function that calls itself internally is a recursive function

Note: Recursive functions function as loops, recursion is prone to “stack overflow” error, so you must add an exit condition return.

// Recursive function: a function that calls itself internally is a recursive function
// Each call opens up a new function
var num = 1;
var i = 0;

function fn() {
    console.log('I'm going to print six sentences.');

    if (num == 6) {
        return; // There must be an exit condition in the recursion
    }
    num++;
    fn();
    console.log(i++);
}
fn();
Copy the code

12.2 Using recursion to find the factorial of 1~n

1 * 2 * 3 * 4 *... n
 function fn(n) {
     if (n == 1) { // End condition
       return 1;
     }
     return n * fn(n - 1);
 }
 console.log(fn(3));
Copy the code

12.3 Finding the Fibonacci sequence using recursion

// Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21...
// The user can input a number n to find the corresponding rabbit sequence value
// We only need to know the first two terms of the user input n (n-1 n-2) to calculate the corresponding sequence value of n
function fb(n) {
  if (n === 1 || n === 2) {
        return 1;
  }
  return fb(n - 1) + fb(n - 2);
}
console.log(fb(3));
Copy the code

12.4 Recursive traversal of data

// We want to make a data object that can be returned by typing an ID number
var data = [{
    id: 1.name: 'goods'.goods: [{
        id: 11.gname: 'the refrigerator.goods: [{
            id: 111.gname: '海尔'
        }, {
            id: 112.gname: 'beauty'}]}, {id: 12.gname: 'Washing machine'}]}, {id: 2.name: 'dress'.goods: [{
        id: 13.gname: '1' fridge.goods: [{
            id: 131.gname: '1' haier
        }, {
            id: 132.gname: '1' beauty]}, {},id: 14.gname: 'Washing Machine 1'}}]];// We want to make a data object that can be returned by typing an ID number
// 1. Use forEach to iterate through each object
function getID(json, id) {
    var res = {};
    json.forEach(function(item) {
        // item-- two array elements
        // If res is not empty, it is already found
        Keys gets the property name of the current Object. The return value is an array
        if (Object.keys(res).length == 0) {
            if (item.id == id) {
                res = item;
                // 2. We want to get the data of the inner layer
                // There should be an array of goods and the array length is not zero
            } else if (item.goods && item.goods.length > 0) { res = getID(item.goods, id); }}});return res;
}

console.log(getID(data, 1));// {id: 1, goods: Array(2)}
Copy the code

13. Shallow and deep copies

13.1 shallow copy

Shallow copies copy only one layer, and deeper object levels copy only references.

// Deep copy copies multiple layers of data at each level.
var obj = {
    id: 1.name: 'andy'.msg: {
        age: 18}};var o = {};
// Method 1:
for (var k in obj) {
    // k is the attribute name obj[k] attribute value
    o[k] = obj[k];
}

// Method 2:
// copy obj to o
Object.assign(o, obj);
o.id = 2;
o.msg.age = 20;
console.log(obj.id); / / 1
console.log(obj.msg.age); / / 20

// Methods 1 and 2 copy only the reference (MSG) of the complex data type. The MSG of o changes, and the corresponding content of obj changes
// For simple datatype (id,name), copy the value directly, o changes, obj does not change

// Method 3:
o = obj;
o.id = 2;
console.log(obj.id); / / 2
// Copy the reference address directly, so everything changes
Copy the code

13.2 deep copy

Deep copy copies multiple layers of data at each level.

// Deep copy copies multiple layers of data at each level.
var obj = {
    id: 1.name: 'andy'.msg: {
        age: 18
    },
    color: ['pink'.'red']};var o = {};
// Encapsulate the function
function deepCopy(newobj, oldobj) {
    for (var k in oldobj) {
        // Determine which data type our attribute value belongs to
        Oldobj [k]
        var item = oldobj[k];
        // 2. Check if the value is an array
        // Note that array judgments are written before objects, because arrays are also objects
        if (item instanceof Array) {
            newobj[k] = [];
            deepCopy(newobj[k], item)
        } else if (item instanceof Object) {
            // 3. Check if the value is an object
            newobj[k] = {};
            deepCopy(newobj[k], item)
        } else {
            // 4. Is a simple data type
            newobj[k] = item;
        }
    }
}
deepCopy(o, obj);

o.msg.age = 20;
console.log(obj.msg.age); / / 18

// Method 2: Convert to a string and then go back
let newobj = JSON.stringify(obj);
newobj = JSON.parse(newobj);
Copy the code

14. Regular expressions

A Regular Expression is a pattern used to match combinations of characters in a string. In JavaScript, regular expressions are also objects.

Refer to MDN for special characters

Regular test tool

14.1 Using regular Expressions

  • /abc/
    • The following conditions are met: Contains ABC
    • Regular expressions do not require quotation marks, either numeric or string

// 1. Use the RegExp object to create a regular expression
var regexp = new RegExp(/ 123 /);
console.log(regexp);

// 2. Use literals to create regular expressions
var rg = / 123 /;
// 3. The test method is used to check whether a string complies with regular expression requirements
console.log(rg.test(123));// true
console.log(rg.test('abc'));// false
Copy the code

14.2 Special Characters

14.2.1 boundary operator

  • ^ Matches the text at the beginning of the line (with whom to start)

  • $matches the text at the end of the line (where it ends)

  • If ^ and $are together, it must be an exact match.

14.2.2 [] Square brackets

You just have to match one of them, one of many

// Character class: [] indicates that there are a series of characters to choose from, and you only need to match one of them
var rg = /[abc]/; // Return true whenever a or b or c is included
console.log(rg.test('baby')); // true
console.log(rg.test('red')); // false
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');

var rg1 = /^[abc]$/; Return true only if the letters are a, B, or C
console.log(rg1.test('aa')); // false
console.log(rg1.test('a')); // true
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');

var reg = /^[a-z]$/; // Each of the 26 letters returns true - representing the range from A to Z
console.log(reg.test('a')); // true
console.log(reg.test('A')); // false
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');

// Character combination
var reg1 = /^[a-zA-Z0-9_-]$/; // 26 letters (uppercase and lowercase), digits 0-9, -, and _ return true
console.log(reg1.test(The '-')); // true
console.log(reg1.test('_')); // true
console.log(reg1.test('! ')); // false
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');
// If there is a ^ in the brackets, it means the opposite
var reg2 = /^[^a-zA-Z0-9_-]$/;
console.log(reg2.test('_')); // false
console.log(reg2.test('! ')); // true
Copy the code

14.2.3 quantifier operator

Quantifiers are used to set the number of occurrences of a pattern.

quantifiers instructions
* Repeat 0 or more times
+ Repeat 1 or more times
? Repeat 0 or 1 times
{n} Repeated n times
{n,} Repeat n times or more
{n,m} Repeat n to m times
// var reg = /^a{3+}$/;
console.log(reg.test('aaaba'));// false

{3,} is greater than or equal to 3
var reg = /^a{3,}$/;
console.log(reg.test('aa'));// false
console.log(reg.test('aaa'));//true

// just make c repeat ABCCC 3 times
var reg = /^abc{3}$/;

// let ABC repeat 3 times
var reg = /^(abc){3}$/;

// {3, 16} is greater than or equal to 3 and less than or equal to 16
var reg = / ^ 3 dec} {$/ a;
console.log(reg.test('aaaaaa'));// true

// Contains only letters, digits, underscores (_), and hyphens (-), and contains 6 to 16 characters.
var reg = / ^ [a - zA - Z0 - _ - 9] 6 16th} {$/; 
Copy the code

14.3 Predefined Classes

Shorthand for some common patterns

// Verify the landline number
var reg = /^\d{3}-\d{8}|\d{4}-\d{7}$/;
var reg = / ^ \ d {3, 4} - \ d {7, 8} $/;

/ / phone number validation: / ^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $/;
$/ ^[1-9]\d{4,}$/;
// nickname validation :/^[\u4e00-\u9fa5]{2,8}$/
Copy the code

14.4 Regular Replaces Replace

Implement the string substitution operation, which can be a string or a regular expression.

// Replace the first one by default
var str = 'abcabc'
var newStr = str.replace(/a/.'ha ha')/ / ha bcabc
// write g after, replace all
var newStr1 = str.replace(/a/g.'ha ha')// ha ha ha BC
// Ignore case I
var str = 'aAbcAba';
var newStr = str.replace(/a/gi.'ha ha')//" ha ha ha ha BC ha ha b ha ha"


// Replace all passion and gay with **
div.innerHTML = text.value.replace(Passion | / gay/g.'* *');
Copy the code

14.5 Retrieving match matches

The match() method extracts a substring of the specified content from a string, returning a new content consisting of matches

var str = 'abc123def';
var patt = / [0-9] + /;
var newArr = str.match(patt); // ["123", index: 3, input: "abc123def", groups: undefined]
Copy the code

15. ES6 (ECMAScript) grammar

15.1 the let

Declare a variable

  • Variables declared by the LET are only valid at the block level
  • Variables declared using the let keyword have no variable promotion
  • Variables declared using the let keyword have the temporary deadband property

Classic Interview questions

// The key point of this problem is that the variable I is global, and the output of the function is the value of I in the global scope.
 var arr = [];
 for (var i = 0; i < 2; i++) {
     arr[i] = function () {
         console.log(i); 
     }
 }
 arr[0] (); arr[1] ();Copy the code

// The key point of this problem is that each loop generates a block-level scope. The variables in each block-level scope are different, and the function executes to output the value of I in its upper (the block-level scope generated by the loop) scope.
 let arr = [];
 for (let i = 0; i < 2; i++) {
     arr[i] = function () {
         console.log(i); 
     }
 }
 arr[0] (); arr[1] ();Copy the code

15.2 const

Declare a constant, which is the amount by which a value (memory address) cannot change

  • Has block-level scope
  • Constants must be assigned when they are declared
  • After a constant is assigned, its value cannot be modified

15.3 Differences between let, const, var

15.4 Deconstructing Assignment

  • Deconstructing assignment involves breaking up data structures and assigning values to variables

  • If the structure is unsuccessful and the variable does not match the number of values, the variable value is undefined

  • Using deconstructed assignment makes it easy to fetch properties and methods from objects

15.4.1 Array Deconstruction

 let [a, b, c] = [1.2.3];
 console.log(a)/ / 1
 console.log(b)/ / 2
 console.log(c)/ / 3
// If the deconstruction fails, the value of the variable is undefined
Copy the code

15.4.2 Object Deconstruction

 let person = { name: 'zhangsan'.age: 20 }; 
 let { name, age } = person;
 console.log(name); // 'zhangsan' 
 console.log(age); / / 20

 let {name: myName, age: myAge} = person; // myName myAge belongs to an alias
 console.log(myName); // 'zhangsan' 
 console.log(myAge); / / 20
Copy the code

15.5 Arrow Functions

The advantage of the arrow function is that it solves some of the problems caused by the this execution environment. For example, the problem of anonymous function this pointing to (anonymous function execution environment is global), including setTimeout and setInterval using this (their this default usually points to window).

  • This is determined by the outer scope and refers to this at function definition time, not execution time.

    • Arrow functions do not have the this binding, and its value must be determined by searching the scope chain. If the arrow function is contained by a non-arrow function, this is bound to the nearest non-arrow function’s this; otherwise, this is undefined.
  • The object created by the literal is scoped to window, and this points to window if it has the arrow function property inside

  • The constructor creates an object whose scope can be understood as the constructor, and whose this refers to the newly created object, so this refers to the object.

  • The arrow function this cannot be changed directly by bind, call, or apply, but can be changed indirectly by changing the direction of this in the scope.

15.5.1 case

  1. Global ordinary functions: function nesting
const obj = { name: 'Joe'} 
function fn () { 
     console.log(this);// This points to an obj object
     return () = > { 
         console.log(this);// This points to the position defined by the arrow function, so the arrow function is defined inside fn, and fn points to obj, so this also points to obj}}const resFn = fn.call(obj); 
 resFn();
Copy the code
  1. The difference between normal functions and arrow functions in literal objects: function nesting
var name = 'window'
var obj1 = {
  name: 'obj1'.foo: function () {
    console.log(this.name)
    return function () {
      console.log(this.name)
    }
  }
}
var obj2 = {
  name: 'obj2'.foo: function () {
    console.log(this.name)
    return () = > {
      console.log(this.name)
    }
  }
}
var obj3 = {
  name: 'obj3'.foo: () = > {
    console.log(this.name)
    return function () {
      console.log(this.name)
    }
  }
}
var obj4 = {
  name: 'obj4'.foo: () = > {
    console.log(this.name)
    return () = > {
      console.log(this.name)
    }
  }
}

obj1.foo()() // 'obj1' 'window'
obj2.foo()() // 'obj2' 'obj2'
obj3.foo()() // 'window' 'window'
obj4.foo()() // 'window' 'window'
Copy the code
  1. The difference between normal and arrow functions in a constructor object: the topic of function nesting
var name = 'window'
function Person (name) {
  this.name = name
  this.foo1 = function () {
    console.log(this.name)
    return function () {
      console.log(this.name)
    }
  }
  this.foo2 = function () {
    console.log(this.name)
    return () = > {
      console.log(this.name)
    }
  }
  this.foo3 = () = > {
    console.log(this.name)
    return function () {
      console.log(this.name)
    }
  }
  this.foo4 = () = > {
    console.log(this.name)
    return () = > {
      console.log(this.name)
    }
  }
}
var person1 = new Person('person1')
person1.foo1()() // 'person1' 'window'
person1.foo2()() // 'person1' 'person1'
person1.foo3()() // 'person1' 'window'
person1.foo4()() // 'person1' 'person1'
Copy the code
  1. The arrow function combines the dot call title

In this case, obj1.foo1.call(obj2)() is equivalent to changing the scope of this in the arrow function indirectly.

var name = 'window'
var obj1 = {
  name: 'obj1'.foo1: function () {
    console.log(this.name)
    return () = > {
      console.log(this.name)
    }
  },
  foo2: () = > {
    console.log(this.name)
    return function () {
      console.log(this.name)
    }
  }
}
var obj2 = {
  name: 'obj2'
}
obj1.foo1.call(obj2)() // 'obj2' 'obj2'
obj1.foo1().call(obj2) // 'obj1' 'obj1'
obj1.foo2.call(obj2)() // 'window' 'window'
obj1.foo2().call(obj2) // 'window' 'obj2'
Copy the code
  • The interview questions
var age = 100;

var obj = {
	age: 20.say: () = > {
		alert(this.age)/ / 100
	}
}

obj.say();// The arrow function this points to the declared scope, while the object has no scope, so the arrow function is defined in the object, but this points to the global scope
Copy the code

15.7 Remaining Parameters

To represent an indefinite number of arguments as an array, the indefinite parameter definition method is a convenient way to declare a function without knowing the parameters

function sum (first, ... args) {
     console.log(first); / / 10
     console.log(args); / / (20, 30)
 }
 sum(10.20.30The remaining parameters are used in conjunction with deconstructionlet students = ['wangwu'.'zhangsan'.'lisi'];
let [s1, ...s2] = students; 
console.log(s1);  // 'wangwu' 
console.log(s2);  // ['zhangsan', 'lisi']
Copy the code

16. Built-in object extensions for ES6

16.1 Array

16.1.1 Extending Operators (Expand Syntax)

  1. Converts an array or object to a comma-separated sequence of arguments
 let ary = [1.2.3]; . ary/ / 1, 2, 3
 console.log(... ary);// 1, 2, 3, equivalent to the following code
 console.log(1.2.3);
Copy the code
  1. Merge array
/ / method
 let ary1 = [1.2.3];
 let ary2 = [3.4.5];
 let ary3 = [...ary1, ...ary2];
 / / method 2ary1.push(... ary2);Copy the code
  1. Convert a class array or traversable object into a true array
let oDivs = document.getElementsByTagName('div'); 
oDivs = [...oDivs];
Copy the code

16.1.2 Constructor method: array.from ()

Converts a pseudo-array or traversable object into a real array

// Define a collection
let arrayLike = {
    '0': 'a'.'1': 'b'.'2': 'c'.length: 3
}; 
// convert to array
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

The // method can also take a second argument, similar to the map method of arrays, which processes each element and places the value in the returned array
 let arrayLike = { 
     "0": 1."1": 2."length": 2
 }
 let newAry = Array.from(arrayLike, item= > item *2)/ / (2, 4]
 // Note: if it is an object, then the attribute needs to be indexed
Copy the code

16.1.3 Instance method: find()

Used to find the first eligible array member, returns undefined if none is found

let ary = [{
     id: 1.name: 'Joe'
 }, { 
     id: 2.name: 'bill'
 }]; 
 let target = ary.find((item, index) = > item.id == 2);// Select a value from the array where id = 2, note that only the first value is matched

Copy the code

16.1.4 Instance method: findIndex()

Used to find the location of the first eligible array member, or -1 if none is found

let ary = [1.5.10.15];
let index = ary.findIndex((value, index) = > value > 9); 
console.log(index); / / 2
Copy the code

16.1.5 Instance method: includes()

Checks whether an array contains a given value, returning a Boolean value.

[1.2.3].includes(2) // true 
[1.2.3].includes(4) // false

Copy the code

16.2 String extension methods

16.2.1 Template Character String

// The template string can be newline
 let html = ` <div>
     <span>${result.name}</span>
     <span>${result.age}</span>
     <span>${result.sex}</span>
 </div> `;
 
// You can call functions in the template string
let greet = `${sayHello()}Hahaha ';
Copy the code

16.2.2 Instance methods: startsWith() and endsWith()

  • StartsWith () : Indicates whether the argument string is at the head of the original string, returning a Boolean value
  • EndsWith () : Indicates whether the argument string is at the end of the original string, returning a Boolean value
let str = 'Hello world! ';
str.startsWith('Hello') // true 
str.endsWith('! ')       // true
Copy the code

16.2.3 Instance method: repeat()

The repeat method means that the original string is repeated n times, returning a new string

'x'.repeat(3)      // "xxx" 
'hello'.repeat(2)  // "hellohello"
Copy the code

16.3 Set Data Structure

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

The Set itself is a constructor used to generate the Set data structure

const s = new Set(a);Copy the code

The Set function can take an array as an argument to initialize.

const set = new Set([1.2.3.4.4]);/ / {1, 2, 3, 4}
Copy the code

16.3.1 Instance methods

  • Add (value) : Adds a value and returns the Set structure itself
  • Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful
  • Has (value) : Returns a Boolean value indicating whether the value is a member of Set
  • Clear () : Clears all members with no return value
 const s = new Set(a); s.add(1).add(2).add(3); // Add values to the set structure
 s.delete(2)             // Delete the 2 value from the set structure
 s.has(1)                // Returns a Boolean value indicating whether there is 1 in the set structure
 s.clear()               // Clear all values in the set structure
 // Note that the value of the element is deleted, not the index represented
Copy the code

16.3.2 traversal

An instance of a Set structure, like an array, has a forEach method that performs some operation on each member and returns no value.

s.forEach(value= > console.log(value))
Copy the code