Comprehensive understanding of class class in es6

In traditional javascript, there are only objects and no concept of classes. It is a prototype based object-oriented language. The characteristic of prototype object is to share its own properties with new objects. Compared with other traditional object-oriented languages, this writing method has a unique feeling! Very confusing!
If you want to generate an object instance, you need to define a constructor first, and then complete it through the new operator. Constructor example:

 

//The function name and the instantiation construct name are the same and capitalized (not mandatory, but it helps to distinguish between constructors and ordinary functions)
function Person(name,age) {
    this.name = name;
    this.age=age;
}
Person.prototype.say = function(){
    return "My name is" + this.name+"this year"+this.age+"Years old";
}
var obj=new Person("laotie",88);//To create an object through a constructor, you must use the new operator
console.log(obj.say());//My name is laotie. I'm 88 years old

Execution process of constructor generation instance:

 

1.When a constructor is used, and new Constructor(),The background will execute implicitly new Object()create object;
2.Give the scope of the constructor to the new object, (that is new Object()The object created), and the object in the function body this On behalf new Object()The object.
3.Execute the code of the constructor.
4.Return new object (direct return in the background);

ES6 introduces the concept of class, which can be defined through the class keyword. The emergence of this keyword makes it clearer in object writing, and it is more like an object-oriented language. If the previous code is changed to ES6, it will look like this:

 

class Person{//Defines a class named Person
    constructor(name,age){//constructor is a construction method used to receive parameters
        this.name = name;//this represents the instance object
        this.age=age;
    }
    say(){//This is a class method. Be careful not to add function
        return "My name is" + this.name+"this year"+this.age+"Years old";
    }
}
var obj=new Person("laotie",88);
console.log(obj.say());//My name is laotie. I'm 88 years old

Attention items

 

1.When declaring a method in a class, never add a function keyword
2.Methods should not be separated by commas, otherwise an error will be reported

As can be seen from the following code, a class is essentially a function. The class itself points to the constructor. So we can think that the class in ES6 is actually another way to write the constructor!

 

console.log(typeof Person);//function
console.log(Person===Person.prototype.constructor);//true

The following code shows that the prototype attribute of the constructor still exists in the class of ES6.
console.log(Person.prototype);// The output is an object
In fact, all methods of the class are defined on the prototype attribute of the class. Code proof:

 

Person.prototype.say=function(){//Defines a method with the same name as in the class. Successfully achieved coverage!
    return "I'm here to prove it. What's your name" + this.name+"this year"+this.age+"Years old";
}
var obj=new Person("laotie",88);
console.log(obj.say());//I'm here to prove it. Your name is laotie. You're 88 years old

Of course, you can also add methods to the class through the prototype attribute. As follows:

 

Person.prototype.addFn=function(){
    return "I passed prototype Newly added method,Name is addFn";
}
var obj=new Person("laotie",88);
console.log(obj.addFn());//I added a new method through prototype. Its name is addFn

You can also use object Assign method to dynamically add methods for objects

 

Object.assign(Person.prototype,{
    getName:function(){
        return this.name;
    },
    getAge:function(){
        return this.age;
    }
})
var obj=new Person("laotie",88);
console.log(obj.getName());//laotie
console.log(obj.getAge());//88

The constructor method is the default method of the constructor of the class. It is called automatically when an object instance is generated through the new command.

 

class Box{
    constructor(){
        console.log("Lala, it's sunny today");//This line of code is executed when the object is instantiated.
    }
}
var obj=new Box();

If the constructor method is not explicitly defined, it will implicitly generate a constructor method. So even if you don't add a constructor, the constructor still exists. The constructor method returns the instance object this by default, but you can also specify the constructor method to return a new object so that the returned instance object is not an instance of this class.

 

class Desk{
    constructor(){
        this.xixi="I'm a little bird! oh";
    }
}
class Box{
    constructor(){
       return new Desk();// this is not used here. It returns a new object directly
    }
}
var obj=new Box();
console.log(obj.xixi);//I'm a little bird! oh

The attributes defined in the constructor can be called instance attributes (i.e. defined on this object). The attributes declared outside the constructor are defined on the prototype, which can be called prototype attributes (i.e. defined on class). The hasOwnProperty() function is used to determine whether the property is an instance property. The result is a Boolean value. True indicates that it is an instance attribute, and false indicates that it is not an instance attribute. The in operator returns true when a given property can be accessed through an object, whether the property exists in an instance or prototype.

 

class Box{
    constructor(num1,num2){
        this.num1 = num1;
        this.num2=num2;
    }
    sum(){
        return num1+num2;
    }
}
var box=new Box(12,88);
console.log(box.hasOwnProperty("num1"));//true
console.log(box.hasOwnProperty("num2"));//true
console.log(box.hasOwnProperty("sum"));//false
console.log("num1" in box);//true
console.log("num2" in box);//true
console.log("sum" in box);//true
console.log("say" in box);//false

All instances of the class share a prototype object, and their prototype is person Prototype, so the proto attribute is equal

 

class Box{
    constructor(num1,num2){
        this.num1 = num1;
        this.num2=num2;
    }
    sum(){
        return num1+num2;
    }
}
//box1 and box2 are both instances of box. Their__ proto__ All point to the prototype of the box
var box1=new Box(12,88);
var box2=new Box(40,60);
console.log(box1.__proto__===box2.__proto__);//true

Thus, you can also add methods to the Class through proto. Rewriting the prototype with the proto attribute of the instance will change the original definition of Class and affect all instances, so it is not recommended!

 

class Box{
    constructor(num1,num2){
        this.num1 = num1;
        this.num2=num2;
    }
    sum(){
        return num1+num2;
    }
}
var box1=new Box(12,88);
var box2=new Box(40,60);
box1.__proto__.sub=function(){
    return this.num2-this.num1;
}
console.log(box1.sub());//76
console.log(box2.sub());//20

Class has no variable promotion, so it needs to be defined before use. Because ES6 will not promote the class declaration to the code header, but ES5 is different. ES5 has variable promotion, which can be used first and then defined.

 

//ES5 can be used first and then defined. There is variable promotion
new A();
function A(){

}
//ES6 cannot be used before being defined. If there is no variable promotion, an error will be reported
new B();//B is not defined
class B{

}

--—END--—

Friends who love this article, welcome to Zhang Peiyue, the official account.

 



Author: Zhang peiyue
Link: https://www.jianshu.com/p/86267fab4878
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Keywords: ECMAScript

Added by vickytam on Mon, 31 Jan 2022 11:41:23 +0200