es5 inheritance es6 inheritance

es5 inheritance es6 inheritance

Code

// es5 继承
function Parent(content){
    
    
    this.content = content
}
Parent.prototype.say = function(){
    
    
    console.log(this.content)
}

// 普通继承缺点:不会继承原型
function Child(content){
    
    
    Parent.call(this, content)
}
let child = new Child('inherit')
console.log(child , 'child ')

// 组合继承: 属性和原型都继承了 多调用一次构造函数多继承了一遍父类的属性 造成内存浪费
function Child_1(content){
    
    
    Parent.call(this, content)
}
Child_1.prototype = new Child_1()
let child_1 = new Child_1('inherit')
console.log(child_1 , 'child_1 ')

// 寄生式继承 属性和原型都继承了 同时解决了内存浪费问题
function Child_2(content){
    
    
    Parent.call(this, content)
}
let p = Parent.prototype
p.constructor = Child_2
Child_2.prototype = p
let child_2 = new Child_2('inherit')
console.log(child_2 , 'child_2 ')

// es6 class 继承
class Parent_{
    
    
    constructor(content){
    
    
        this.content = content
    }
    say(){
    
    
        console.log(this.content)
    }
}
class Child_ extends Parent_{
    
    
    constructor(content){
    
    
        super(content)
    }
}
console.log(Child_ , 'Child_ ')

Guess you like

Origin blog.csdn.net/dzhi1931/article/details/109830542