ES6 class class and inheritance

class

1 -------- the following code defines a "class". You can see that there is a constructor method in it, which is the construction method

   class Box{
       constructor(a,b){
           console.log(a+b);//8
       }
       play(){
       }
   }
   let b=new Box(5,3)  //Instantiation, when instantiated, executes the constructor
   
    console.log(b.constructor === Box)//true  
    //Object's constructor is the current class name
    
   console.log(b.constructor === Box.prototype.constructor)//true  
   //b is an instance of the Box class. Its constructor method is the constructor method of the Box class prototype

Object's constructor is the current class name
In other languages, the class name is the same as the constructor name, because the class needs to instantiate the object, and the constructor must be executed first. In some languages, there can be multiple constructors
There can only be one native js constructor, and the constructors of all classes are written as constructor functions. This constructor is actually the current class name



==2 ----------- because the constructor in js is the class name, we can judge whether an object belongs to this class according to whether its constructor is a class name

//The object created by instantiation is a class. You can judge whether it belongs to this class according to the constructor
	var arr=new Array(1,2,3);
	console.log(arr.constructor.name);//Array
	//Printing constractor alone is a function
	//The constructor has a name attribute that is the class name of this class
	console.log(arr.constructor===Array);//true
	
	var date=new Date();
	console.log(date.constructor===Date);////true
	
	var reg=/a/g;
	console.log(reg.constructor===RegExp);////true
	
	var div=document.createElement("div");
	console.log(div.constructor===HTMLDivElement);//true

3 -------- in a class, except that the local variable in the function is the attribute in the class, and this in the class is the instantiated object

//The following code is only used to define a human class and how to use it. Chinese programming is not allowed
   class man{
       eyes=2;
       mouse=1;
       ear=2;
       hands=2;
       foots=2;
       name;//Created a man class with the above properties
       constructor(_name){
          this.name=_name;
       }
       walk(){//man's class has a method of walk() run() eat() fire()
           console.log(this.name+"go")
       }
       run(){
           console.log(this.name+"run")
       }
       eat(){
           console.log(this.name+"eat")
       }
       fire(){
           console.log(this.name+"Make a fire")
       }
   }

  var xiaoming=new man("Xiao Ming");
  //Create an instantiated object of xioaming, which has all the methods and properties of the man class, and can be used directly
  xiaoming.eat();
  xiaoming.run();
  var xiaohua=new man("Floret");
  //An instantiated object of xioahua is created
  xiaohua.run();
  xiaohua.fire();

1. The object instantiated by the constructor is the instance object of this class (for example, the code xiaohua is the object instantiated by the constructor, which is the instance object of this class)
2. Therefore, this instance object has all the properties and methods of the class. For example, the above code xiaohua has all the properties and methods of the class man
3. This instance object can call its own methods and properties
4. Because the constructor generates the instantiated object by default, return cannot be used in the constructor to return other contents. The constructor does not allow to write return
5. Who calls the method? this is the instance object in the function of the class


4 ------ here's a small exercise. I'm used to thinking about programming from the bottom. Here are two different codes that generate 10 random small squares. Let's see what's the difference
The first is:

 function randomColor(){
         var col="#";
         for(var i=0;i<6;i++){
             col+=Math.floor(Math.random()*16).toString(16);//Randomly generate color
         }
         return col;
     }

  class Rect{//Class names are capitalized and humped
      elem;
      constructor(w,h,c){
          this.elem=this.createRect(w,h,c);//This here refers to this class
      }
      createRect(w,h,c){//How to create a div
          let div=document.createElement("div");
          Object.assign(div.style,{
              width:w+"px",
              height:h+"px",
              backgroundColor:c,
              float:'left'
          });
          return div;
      }
      appendTo(parent){//Add the created div to the parent element
          parent.appendChild(this.elem);
      }
      play(){
          console.log("aaa");
      }
      run(){
          console.log("1");
      }
  }

  
  for(var i=0;i<10;i++){
      var w=Math.floor(Math.random()*50+50);
      let rect=new Rect(w,w,randomColor());//Instantiate 10 objects, randomly generate width, height and color
      rect.appendTo(document.body);//Add to body
  }

Second species:

function randomColor(){
        var col="#";
        for(var i=0;i<6;i++){
            col+=Math.floor(Math.random()*16).toString(16);//Randomly generate color
        }
        return col;
    }
class Rect1{
    elem;
    w=50;
    h=50;
    c="red";
    constructor(){
        this.elem=this.createRect();
    }
    createRect(){
        let div=document.createElement("div");
        Object.assign(div.style,{
            width:this.w+"px",
            height:this.h+"px",
            backgroundColor:this.c
        });
        return div;
    }
    appendTo(parent){
        parent.appendChild(this.elem);
    }
    setWH(w,h){
        this.elem.style.width=w+"px";
        this.elem.style.height=h+"px";
    }
    setBg(color){
        this.elem.style.backgroundColor=color;
    }
    
}

for(var i=0;i<10;i++){
    var w=Math.floor(Math.random()*50+50);
    let rect=new Rect1();//Instantiate 10 objects, randomly generate width, height and color
    rect.setWH(w,w);
    rect.setBg(randomColor())
    rect.appendTo(document.body);//Add to body
}

The effect of the two implementations is the same. The first is a semi object-oriented programming method. The second is to put each variable as an attribute in a class, which can better reflect the object-oriented programming idea

5 ------ inheritance-------

Class can be inherited through the extends keyword, which is much clearer and more convenient than ES5's implementation of inheritance by modifying the prototype chain.

For example, to inherit the Rect1 class, you only need to use extends to inherit the properties and methods of Rect1. After inheriting the parent class, you must use super() in the constructor to call the constructor of the super class. What is the super class? What is it

class Circle1 extends Rect1{
       constructor(r){
           // After inheriting the parent class, the constructor of the superclass must be called in the constructor.
           super();//The constructor of a superclass. What is a superclass? What is this

       }
   }

For example, now I want to create ten circles. I just need to add some attributes to the code of the 10 blocks created above. Then I don't need to write a new class. I can inherit its attributes on the original class, and then add new attributes

The first method of the above code

//Randomly generated color function
function randomColor(){
    var col="#";
    for(var i=0;i<6;i++){
        col+=Math.floor(Math.random()*16).toString(16);//Randomly generate color
    }
    return col;
}


//Create parent class
class Rect{
	    elem;
	    constructor(w,h,c){
	        this.elem=this.createRect(w,h,c);//This here refers to this class
	    }
	    createRect(w,h,c){//How to create a div
	        let div=document.createElement("div");
	        Object.assign(div.style,{
	            width:w+"px",
	            height:h+"px",
	            backgroundColor:c,
	            float:'left'
	        });
	        return div;
	    }
	    appendTo(parent){//Add the created div to the parent element
	        parent.appendChild(this.elem);
	    }
	    play(){
	        console.log("aaa");
	    }
	    run(){
	        console.log("1");
	    }
	}


//inherit
class Circle extends Rect{
      constructor(w,h,c,r){
          super(w,h,c);//The constructor of a superclass has parameters, so the required parameters must be passed in the subclass
          this.elem.style.borderRadius=r+"%";
      }
      setBorder(w,c){
          this.elem.style.border=w+"px solid "+c;
      }
      // Because the method of the subclass is the same as that of the parent, it will override
      play(){
          console.log("bbb");
      }
      run(){
          super.run();//Execute the run method of the superclass, and continue to execute the following
          console.log("2");
      }
  }

//instantiation
for(var i=0;i<10;i++){
    var w=Math.floor(Math.random()*50+50);
     let c=new Circle(w,w,randomColor(),50);
     c.setBorder(2,"red")
     c.appendTo(document.body);
     c.play();
     c.run();
 }

The second method of the above code

//Randomly generated color function
function randomColor(){
    var col="#";
    for(var i=0;i<6;i++){
        col+=Math.floor(Math.random()*16).toString(16);//Randomly generate color
    }
    return col;
}

//Create parent class
class Rect1{
      elem;
      w=50;
      h=50;
      c="red";
      constructor(){
          this.elem=this.createRect();
      }
      createRect(){
          let div=document.createElement("div");
          Object.assign(div.style,{
              width:this.w+"px",
              height:this.h+"px",
              backgroundColor:this.c
          });
          return div;
      }
      appendTo(parent){
          parent.appendChild(this.elem);
      }
      setWH(w,h){
          this.elem.style.width=w+"px";
          this.elem.style.height=h+"px";
      }
      setBg(color){
          this.elem.style.backgroundColor=color;
      }
      
  }

//inherit
 class Circle extends Rect1{
      constructor(){
          super();//Using super() to call the constructor of a superclass
      }
      borderR(r){
          this.elem.style.borderRadius=r+"%";
      }
      setBorder(w,c){
          this.elem.style.border=w+"px solid "+c;
      }
      // Because the method of the subclass is the same as that of the parent, it will override
      play(){
          console.log("bbb");
      }
  }

  //instantiation
 for(var i=0;i<10;i++){
	    let cir=new Circle();//Create an object instance
	    cir.borderR(50);//Method setting in subclass border radial
	    var w=Math.floor(Math.random()*5+1);
	    cir.setBorder(w,randomColor());//Method setting border in subclass
	    cir.setBg(randomColor());//Methods in parent class generate color randomly
	    cir.appendTo(document.body)//Methods in the parent class add elements to the page
 }

The effect is as follows:

Published 8 original articles, won praise 0, visited 41
Private letter follow

Keywords: Programming Attribute

Added by Eric! on Sat, 11 Jan 2020 18:04:29 +0200