The "class" class in ES6

In ES6, you can use the class keyword to declare a class. A class can be regarded as a syntactic sugar . Most of its functions can be achieved by ES5. The new class writing method is used to make the object prototype writing method clearer. More like the syntax of object-oriented programming.

1. Basic creation of classes

class Animal{
    constructor(name,age,weight){
    this.name = name
    this.age = age
    this.weight = weight
    }
    sayName(){
    console.log(this.name)
    }
    
    static sAttr = '我是静态属性'
    static sMethod(){
    console.log('我是一个静态方法')
    }
}

2. The constructor method in the class

The constructor method is the default method of the class. When an object instance is generated through the new command, this method is automatically called. A class must have a constructor method, if not explicitly defined, an empty constructor method will be added by default. The properties in the constructor are private properties of the instance.

3. Methods defined directly in the body of the class

The method directly defined in the class body can be regarded as the public method of all instances, which is equivalent to the method in the prototype object (prototype) in es5, and all instances can be called

4. Static properties and static methods in the class body

In the class body, the properties and methods declared with the static keyword are static properties and static methods, which are equivalent to the static properties and static methods in the constructor in ES5, and can only be accessed and called by the constructor.

5. Class inheritance

5.1 class inheritance is done using the extends keyword

class Dog extends Animal {//相当于原型链继承
  constructor(name, age, weight, type) {
    super(name, age, weight)//这里相当于经典继承
    this.type = type
  }
}

5.2 If the subclass provides a constructor, it must explicitly call super. The super here is equivalent to the classic inheritance in ES5 (borrowing constructor inheritance), and the use of super here is equivalent to Animal.call(this) in ES5.

 5.3 In the inheritance of ES6 classes, subclasses can not only inherit the instance properties and instance methods of the parent class, but also inherit the static properties and static methods of the parent class.

console.log(Dog.sAttr);
Dog.sMethod()

The printed results are as follows:

Guess you like

Origin blog.csdn.net/LLL3189860667/article/details/126945920