常见继承方式

原型链+借用构造函数的组合继承

function parent(val){
    this.val=val;
}
parent.prototype.getvalue=function(){
    console.log(this.val);
}
function Child(val){
    parent.call(this,val);
}
Child.prototype=new parent();
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);

在子类的构造函数中通过parent.call(this)继承父类的属性,然后改变子类的原型为new parent()来继承父类函数。
这种继承的方式,优点在于构造函数可以传参,不会与父类引用属性共享,可以复用父类的函数,缺点是继承父类函数的时候调用父构造函数,导致子类的原型上多了不需要的父类属性,存在内存浪费。

寄生组合继承(优化上一种组合继承)

function parent(val){
    this.val=val;
}
parent.prototype.getvalue=function(){
    console.log(this.val);
}
function Child(val){
    parent.call(this,val);
}
//Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。 
Child.prototype=Object.create(parent.prototype,{
    constructor:{
        value:Child,
        enumerable:false,
        writable:true,
        configurable:true
    }
});
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);

将父类的原型赋值给子类,即解决了无用的父类属性问题,正确找到子类的构造函数。

ES6中class继承

class可以通过extends关键字实现继承,还可以通过static关键字定义类的静态方法。class关键字只是原型的语法糖,js继承依旧是基于原型实现的。

class parent{
    constructor(val){
        this.val=val;
    }
    getvalue(){
        console.log(this.val);
    }
}
class Child extends parent{
    constructor(val){
        super(parent);
        this.val=val;
    }
}
var child=new Child(1);
child.getvalue();
console.log(child instanceof parent);
function inheritPrototype(subType, superType){
    var prototype = Object.create(superType.prototype);       //创建对象
    prototype.constructor = subType;                   //增强对象
    subType.prototype = prototype;                     //指定对象
}

class实现继承核心在于使用extends表明继承自哪个父类,并且在子类构造函数中必须调用super,因为类似parent.call(this,val)

你可能感兴趣的:(常见继承方式)