Inheritance of class in ES6

Posted by luketheduck on Fri, 27 Mar 2020 16:00:53 +0100

Inheritance of class in ES6

Parent class (base class)

Subclass

extends keyword

//Parent class
class Human{
    //Constructor of the parent class
    constructor(name,age,sex,hobby){
        this.name=name
        this.age=age
        this.sex=sex
        this.hobby=hobby
    }

    desc(){
        const {name,age,sex,hobby}=this
        console.log(`My name is ${ name },I am this year ${ age }My gender is: ${ sex },My hobbies are: ${ hobby }`)
    }

    eat(){
        console.log("Barking")
    }
}

//Subclass front end Engineer
class FEEnginner extends Human{
    constructor(name,age,sex,hobby,skill,salary){
        super(name,age,sex,hobby)//stay this Previous call super,It's actually calling the constructor of the parent class
        this.skill=skill
        this.salary=salary
    }

    say(){
        console.log(this.skill.join(","))
    }
}

const feer=new FEEnginner(
    "cyy",
    18,
    "female",
    "study",
    ["es6","vue","react"],
    "1k"
    )
console.log(feer)

//Call the method of the parent class
feer.desc()
//Call subclass's own methods
feer.say()

 

 

Professional system of simulated online games
Parent class: represents a role
Subclass: represents a professional role

class Character{
    //Constructor of the parent class
    constructor(name,sex){
        this.name=name
        this.sex=sex
        this.skill=[]//Skill
    }
}

//Sub Wizard
class Wizard extends Character{
    constructor(name,sex){
        super(name,sex)//stay this Previous call super,It's actually calling the constructor of the parent class
        this.initSkill()
    }

    //Initialize skills
    initSkill(){
        this.skill=[
            {
                name:"Avada Kedavra",
                mp:666,
                level:999
            },
            {
                name:"Guardians curse",
                mp:333,
                level:888
            }
        ]
    }
}

 

Other content of super keyword

super
1. Called as parent constructor
2. Called as object

The first way, as shown above

The second way can be divided into two ways:

1. Accessing super - > parent prototypes in non static methods
2. Access super - > parent class in static method
When super is called, this of the parent class is always this of the child class

//super Called as object

//Parent class
class Human{
    //Constructor of the parent class
    constructor(name,age,sex,hobby){
        this.name=name
        this.age=age
        this.sex=sex
        this.hobby=hobby
    }

    desc(){
        const {name,age,sex,hobby}=this
        console.log(`My name is ${ name },I am this year ${ age }My gender is: ${ sex },My hobbies are: ${ hobby }`)
    }

    eat(){
        console.log("Barking")
    }

    checkThis(_this){
        console.log(_this===this)//this Is the parent class. this,_this It's a subclass passed from a subclass this
    }

}

//Static attribute
Human.total=10000

//Subclass front end Engineer
class FEEnginner extends Human{
    constructor(name,age,sex,hobby,skill,salary){
        super(name,age,sex,hobby)//stay this Previous call super,It's actually calling the constructor of the parent class
        this.skill=skill
        this.salary=salary
    }

    say(){
        //Access in non static methods super -> Parent prototype
        //console.log(super)//It's a mistake
        console.log(super.eat)//It's a mistake
        super.eat()
        // true In call super Of the parent class this Always subclass this
        super.checkThis(this)//Subclass this Pass the past
    }    

    static test(){
        //Access in static method super -> Parent class
        console.log(super.name)//Human
        console.log(super.total)//10000
    }
}

const feer=new FEEnginner(
    "cyy",
    18,
    "female",
    "study",
    ["es6","vue","react"],
    "1k"
    )

//Call subclass's own methods
feer.say()
FEEnginner.test()//Call static method

 

 

Simple polymorphism

The same interface, do different things in different situations

Same interface, different performance

In js, an interface can be understood as a method that needs to be implemented by a subclass

//polymorphic
//If a subclass has a method with the same name as its parent, it will execute its own method and will not go to the parent's
class Human{
    say(){
        console.log("I am a human")
    }
}

class Man extends Human{
    say(){
        super.say()//Call the method with the same name of the parent class
        console.log("I'm a little brother")
    }
}

class Woman extends Human{
    say(){
        super.say()//Call the method with the same name of the parent class
        console.log("I'm little sister")
    }
}

new Man().say()
new Woman().say()

 

 

Overload demonstration: three cases

//Reload Demo 1
class simpleCalc{
    add(...args){
        if(args.length===0) return this.zero()
        if(args.length===1) return this.one(args)
        return this.sum(args)
    }

    zero(){
        return 0
    }

    one(args){
        return args[0]
    }

    sum(args){
        //accumulation
        return reduce((a,b)=>a+b,0)
    }
}

 

//Reload Demo 2
function post(url,header,params){
    //If there is no third parameter, the second parameter passed in is assigned to the params,header Default is null
    if(!params){
        params=header
        header=null //undefind It's fine too

    }
}
post("https://baidu.com",{
    a:1,
    b:2
})

 

//Reload demo 3
//Methods must be implemented by subclasses, or errors will be reported

//Mapping table
const ModelMap={
    "Red eye zombies":1,
    "Pumpkin essence":2,
    "Cyclops":3,
    "Green eyes zombies":4,
}
//Basic monsters
class Monster{
    constructor(name,level,model){
        this.name=name
        this.level=level
        this.model=model
    }

    attack(){
        throw Error("Must be implemented by subclass`attack`Attack method")
    }
}

//Subclass red eye zombies
class RedEyeZombie extends Monster{
    constructor(name,level,model){
        super("Red eye zombies",10,ModelMap["Red eye zombies"])
    }
}

//Subclass green eyed zombies
class GreenEyeZombie extends Monster{
    constructor(name,level,model){
        super("Green eyes zombies",20,ModelMap["Green eyes zombies"])
    }

    attack(){
        console.log("Green eyed zombies attack")
    }
}

const gez=new GreenEyeZombie()
gez.attack()

const rez=new RedEyeZombie()
rez.attack()

 

 

Inheritance in ES5

//ES5 Implementation of inheritance in
//Not real inheritance, but operation on prototype chain

//1,Using constructors (cannot inherit methods on prototypes)
//Parent class
function P(){
    this.name="parent";
    this.gender=2;
    this.say=function(){
        console.log("Okay okay, I'll be there");
    }
}
P.prototype.test=function(){
    console.log("I'm a prototype approach");
}
//Subclass
function C(){
    P.call(this);//A way to implement inheritance
    this.name="child";
    this.age=18;
}
var c=new C();
c.say();
//c.test();//Cannot inherit method on Prototype


//The solution is to change the prototype of a subclass into an instance of a parent class
function P2(){
    this.name="parent";
    this.gender=2;
    this.say=function(){
        console.log("Okay okay, I'll be there");
    }
}
P2.prototype.test=function(){
    console.log("I'm a prototype approach");
}
//Subclass
function C2(){
    P2.call(this);//A way to implement inheritance
    this.name="child";
    this.age=18;
}
C2.prototype=new P2();//hold C2 The prototype of P2 (because P2 Instances of can access P2 Prototype approach)

var c2=new C2();
c2.say();
c2.test();//Succeed in inheriting the method on the prototype

Topics: Javascript Vue React Attribute