current position:Home>Front end learning notes - ES6

Front end learning notes - ES6

2021-08-27 02:00:19 Atomic

One 、 Basic grammar

1. brief introduction

Tradition JS Objects are created through **「 Constructors 」**, for example :

  //  Create objects through constructors 
    function Person(name,age){
        this.name=name;
        this.age = age;
    }
    //  Create examples 
    let p1 = new Person(" Xiaohong ",18);
    console.log("p1:",p1)
    // Person Of prototype and p1 Of __proto__ Point to the same object 
    console.log(Person.prototype === p1.__proto__) // true
 Copy code 

Basically ,ES6 Of class Can be seen as just a Grammatical sugar , Most of its functions ,ES5 Can do it , new class The writing method is just to make the writing method of the object prototype clearer 、 It's more like the syntax of object-oriented programming .

use class Rewrite the syntax as follows :

class PersonCopy{
        constructor(name,age){
            this.name=name;
            this.age=age;
        }
        run(){
            console.log(this.name +" is running")
        }
    }
    let p2 = new PersonCopy(" Xiao Ming ",12);
    console.log("p2:",p2)
    console.log(typeof PersonCopy); // function 
    console.log(PersonCopy.prototype.constructor===PersonCopy) //true
    p2.run();
    
    
 Copy code 

It can be learned that :

  • The data type of a class is a function
  • The class itself points to the constructor

and :

  • Instance properties are added to objects
  • The method is defined to the prototype object prototype Upper , Each instance shares the same method
{
    "name": " Xiao Ming ",
    "age": 12
    
    [[prototype]]:{
     constructor:f()  class PersonCopy,
     run: f run()
    }
}
 Copy code 

amount to :

 function PersonCopy(name,age){
        this.name = name;
        this.age =age;
    }
    //  Method is added to the prototype object , All instances share . So there will only be one run Function object 
    //  Instead of creating one for each object run Function object 
    PersonCopy.prototype.run = function(){
        console.log(this.name +" is running")
    }
    let p3 = new PersonCopy(" Xiao Wang ",13)
    p3.run() //  Xiao Wang  is running
 Copy code 

Because the methods of the class are defined in the class prototype Upper , So you can go through Object.assign() Method adds multiple methods to the class at once :

Object.assign(PersonCopy.prototype,{
        toString(){},
        toValue(){}
    })
 Copy code 

2.constructor

constructor The method is class The default method for , adopt new When the command generates an object instance , Call this method automatically . A class must have constructor Method , If not explicitly defined , An empty one constructor Method will be added by default .

Class must use new call , Otherwise, an error will be reported . This is a major difference between it and a normal constructor , The latter need not new It can also be executed .

And ES5 equally , An instance's properties are not explicitly defined in itself ( Which is defined in this On the object ), Otherwise it's all defined on the prototype ( Which is defined in class On ).

3.getter and setter

  class Man{
        constructor(){} //  Don't write 

        //  Will give prototype Add a name attribute 
        get name(){
            return this.nickname;
        }
        set name(name){
            this.nickname = name;
        }
    }
    let m = new Man();
    console.log(m);
    m.name="hello";
    console.log(m.name) //hello
    console.log(m.nickname); //hello
    m.hasOwnProperty('name') // false
    m.hasOwnProperty('nickname')  //true
    Man.prototype.hasOwnProperty('name') // true
 Copy code 

4. Property expression

Property name of class , You can use the expression . Both properties and methods can use expressions .

    //  Property expression 
    let prop1 = "name";
    let prop2 = "run";
    class Course{
        constructor(name){
            this[prop1] = name;
        }
        [prop2](){
            console.log(prop2)
        }
    }
    let c = new Course(" Basics ");
    console.log(c)
    console.log(c.name)
    c.run()
 Copy code 

5.class expression

Same as function , Classes can also be defined in the form of expressions .


    const A = class B{
        getClassDeclareName(){
            return B.name + A.name; // A.name It's fine too 
        }
    }
    let a = new A();
   console.log( a.getClassDeclareName())
   console.log(A.name) // B
   console.log(B.name)  // error
 Copy code 

The name of this class is B, But it can only be used inside a class , Only... Can be used externally A.A It can be used both internally and externally .

6. Static methods

The class is the stereotype of the instance , All methods defined in the class , Will be inherited by the instance . If it's before a method , add static keyword , Means that the method will not be inherited by the instance , It's called directly from the class , This is called a “ Static methods ”.

    class A{
        constructor(name){
            this.name = name;
        }

        run(){
            console.log(this.name +" is running")
        }
        static step(){
            console.log(this.name +" is step") //  here this Pointing class A
        }
    }
    let a1 = new A(" Xiaohong ");
    
    console.log("a1",a1)
    a1.run()
    A.step()
    a1.step(); //error  Instance does not have this method 
 Copy code 
  • An error will be reported when an instance calls a static method
  • If the static method contains this keyword , This this Refers to the class , Not an instance
  • Static and non static methods can have the same name , Because one is an instance , One is class . as follows : call a1.step() It won't be wrong , Calling a non static method step
    class A{
        constructor(name){
            this.name = name;
        }
        run(){
            console.log(this.name +" is running")
        }
        step(){
            console.log(" Example method step")
        }
        static step(){
            console.log(this.name +" is step") //  here this Pointing class A
        }
    }
    let a1 = new A(" Xiaohong ");
    
    console.log("a1",a1)
    a1.run()
    A.step()
    a1.step(); //  Example method step
 Copy code 

7. A new way to write instance properties

Instance attributes Except for the definition in constructor() Method this above , It can also be defined in class Top of .

  class B{
        name;
        age;
        getName(){
            return this.name;
        }
        setName(value){
            this.name = value;
        }
    }
    let b =new B();
    b.setName("hello")
    console.log(b)
    console.log(b.getName())
 Copy code 

8. Static attribute

Static attribute refer to Class Its own attributes , namely Class.propName, It's not defined in the instance object ( this ) Properties on .

 //  How to write it 1
    class A{

    }
    A.foo=1;
    let a = new A();
    console.log(A.foo);  //1 
    console.log(a.foo) // undefined

    //  How to write it 2
   class B{
       static foo = 1;
   }
   let b = new B();
   console.log(B.foo) //1 
   console.log(b.foo) // undifined
 Copy code 

at present , It's just the way it's written 1 feasible , because ES6 Make it clear ,Class Internal only Static methods , No, Static attribute .

How to write it 2 Just a proposal .

9. Private methods and private properties

nothing

10.new.target

A little

Two 、 Inherit

1. brief introduction

Class Can pass extends Keyword implementation Inherit , This is more than ES5 By modifying the prototype chain to achieve inheritance , Be much clearer and more convenient .

        class A{
            constructor(username,password){
                this.username = username;
                this.password = password;
                console.log("A constructor")
            }
            static run(){
                console.log("run")
            }
        }
        class B extends A{
            constructor(sex,username,password){ 
                console.log("B constructor")
                super(username,password);
                this.sex = sex;
            }
        }
        let b = new B(" male ","admin","1234")
        console.log(b)
        B.run() //  Inherit the static methods of the parent class 
 Copy code 

Subclasses must be constructor Call in method super Method , Otherwise an error will be reported when a new instance is created . This is because of the subclass itself this object , You must first complete the molding through the constructor of the parent class , Get the same instance properties and methods as the parent class , It is then processed , Plus the subclass's own instance properties and methods . If you don't call super Method , Subclasses don't get this object .

  • The subclass must call the constructor of the parent class
  • The constructor of the parent class must be in use this Call before keyword
  • Static methods of the parent class , It will also be inherited by subclasses

2.Object.getPrototypeOf()

Object.getPrototypeOf Method can be used to get a parent class from a subclass .

console.log(Object.getPrototypeOf(B) === A) // true
 Copy code 

3.super keyword

  • super() Call the parent constructor
  • As an object , In the ordinary way , Points to the prototype object of the parent class ; In a static method , Point to the parent class

copyright notice
author[Atomic],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827020016977d.html

Random recommended