ES6: He is here, he is here for class!

ES6: introduction of class

Overview

  • ES6's class grammar is just a syntactic sugar, which can also be implemented in ES5. The new class grammar is just to make the writing of object prototypes clearer and more like object-oriented programming grammar.
class Point{
    
    
    constructor(x,y){
    
    
        this.x = x;
        this.y = y;
    }
    toString(){
    
    
        console.log( '(' + this.x + ',' + this.y + ')');
    }
}

// 调用
let a = new Point(1,2);
a.toString();

//输出
(1,2)
  • Calling a method on an instance of a class is actually calling a method of the prototype;

  • The methods defined inside the class are not enumerable;

  • The class must be called with new , otherwise an error will be reported;

class expression

  • Like functions, class can also be defined in the form of expressions;
const myclass = class me{
    
    
    getClassName(){
    
    
        return me.name;
    }
}

let a = new myclass();
a.getClassName();

// 输出
"me"
  • As can be seen from the above example, me is only useful in internal classes, and the variable name myclass is still used when calling externally;

No variable promotion

  • There is no variable promotion for the class, so it cannot be called before the class is defined;

Private methods and properties

  • The private keyword is not provided in the ES6 class, but there is currently a proposal to use # as a private sign
class Me{
    
    
    #name
    #age = 20
    // #getmoney() {return 100}
    constructor(name){
    
    
        this.#name = name;
    }
    getit(){
    
    
        console.log('age:' + this.#age);
    }

}

let a = new Me('yivi');
a.getit();

//输出
age:20


//如果尝试访问私有属性
a.#name;
//报错
“Private field '#name' must be declared in an enclosing class

the point of this

  • If there is this inside the class, it will point to the instance of the class by default. But sometimes using this method alone may report an error.
class Logger{
    
    
    printName(name = 'yivi'){
    
    
        this.print(`${
      
      name},yyds!`);
    }
    
    print(text){
    
    
        console.log(text);
    }
}

const logger = new Logger();
const {
    
    printName}  = logger;
printName(); 	//报错
  • In the above code, this points to the instance by default, but if extracted and used alone, this will point to the current operating environment;
  • The solution is: store this when defining the class;
//方法1

class Logger{
    
    
    constructor(){
    
    
        // 将当前this绑定到printName函数上
        this.printName = this.PrintName.bind(this);
    }
    
    printName(name = 'yivi'){
    
    
        this.print(`${
      
      name},yyds!`);
    }
    
    print(text){
    
    
        console.log(text);
    }
}

const logger = new Logger();
const {
    
    printName}  = logger;
printName(); 	//“yivi,yyds!”
  • You can also use arrow functions
// 方法2
class Logger{
    
    
    constructor(){
    
    
        this.printName = (name = 'yivi')=>{
    
    
            this.print(`${
      
      name},yyds!`)
        }
    }
}

getter和setter

  • Inside the class, you can also set the get and set keywords to set the value function and the value function of a certain attribute.
class Myclass{
    
    
    constructor(){
    
    }
    get prop(){
    
    
        return 'i am getter!';
    }
    set prop(val){
    
    
        console.log("prop set as "+ val);
    }
}

let init = new Myclass();
init.prop =  123;
init.prop;

//prop set as 123
//i am getter

Static methods and static properties

  • The class is equivalent to the prototype of the instance. The static keyword is added before the function of the class, which represents a static method, which can only be accessed through the class, and the instance will not inherit its methods.
class Foo{
    
    
    static mymethod(){
    
    
        console.log('i am static!');
    }
}

let a = new Foo();
Foo.mymethod();
a.mymethod();

// i am static!
// TypeError: foo.mymethod is not a function
  • The static method of the parent class can be inherited by the child class! The subclass can call the super class method through super.
class Father{
    
    
    static mymethod(){
    
    
        console.log('i am static!');
    }
}

class Son extends Father{
    
    
    static sonmethod(){
    
    
        console.log('hello!' + super.mymethod() );
    }
}

Son.mymethod();
// i am static!

Son.sonmethod();
// hello!i am static!
  • Static properties are the same as static methods, and the static keyword is also added before the properties.

new.target attribute

  • ES6 defines a new.target property inside the class, which returns the constructor of the new command lock function
class Person{
    
    
    name;
    constructor(name){
    
    
        if(new.target == Person){
    
    
            this.name = name;
        }else{
    
    
            throw new Error('请使用new生成实例');
        }
    }
}

let a = new Person('yivi');
  • When the subclass inherits the parent class, new.,target will return to the subclass!
class father{
    
    
    constructor(){
    
    
        console.log(new.target == father);
    }
}

class son extends father{
    
    
    constructor(){
    
    
        super();
    }
}

let a = new son();
// false;

About this of subclass

  • In the subclass's constructor, after calling super, the this keyword can be used, otherwise an error will be reported; this is because the subclass does not have its own this object, but only inherits the this object of the parent class.
  • If the subclass does not define a constructor, a constructor containing the super keyword will be automatically added.
class Father{
    
    }
class Son extends Father{
    
    
    constructor(...args){
    
    
        //自动添加
        super(...args);
    }
}

let a = new Son();
a instanceof Father;
a instanceof Son;

// true
// true

super keyword

  • The super() method can only be used in the constructor attribute of the subclass, and it will report an error when used in other places!

  • The super keyword refers to the prototype object of the parent class as an object in ordinary methods, and refers to the parent class in static methods.

class A{
    
    
    constructor(){
    
    
        this.p = 123;
    }
}

class B extends A{
    
    
    constructor(){
    
    
        super();
        // 这里的super指向A.prototype
        console.log(super.p);
    }
    get m(){
    
    
        // 这里的super指向A
        console.log(super.p);
    }
}

let a = new B();
a.m;
// 123
// undefined
  • Es6 stipulates that when the super class method is called through super, super will bind the this of the subclass. In other words, the super at this time is the this of the subclass
class A{
    
    
    constructor(){
    
    
        this.x = 1;
    }
    print(){
    
    
        console.log(this.x);
    }
}


class B extends A{
    
    
    constructor(){
    
    
        super();
        this.x = 2;
    }
    getx(){
    
    
        super.print();
    }
}

let a = new B();
a.getx();
// 2;

Class prototype and __proto__ attributes

  • The __proto__ attribute of the subclass indicates the inheritance of the constructor, pointing to the parent class;
  • The __proto__ attribute of the prototype attribute of the subclass indicates the inheritance of the method, pointing to the prototype of the parent class;
class A{
    
    }
class B extends A{
    
    }

B.__proto__ === A	//true
B.prototype.__proto__  === A.prototype	//true

Guess you like

Origin blog.csdn.net/yivisir/article/details/108781805