继承

117 阅读1分钟

ES5

原型链继承

function Parent(){
    this.name="lisa";
}
function Child(){}
Child.prototype=new Parent();
let child1=new Child()
console.log(child1.name); // lisa

通过原型链实现继承,不能使用对象字面量的方法创建原型,因为重写原型时,会截断原型链,之前实例化对象无法继承。

构造函数继承

function Parent(name){
    this.name=name;
}
function Child(){
    Parent.call(this,"lisa")
}
let child1=new Child();
console.log(child1.name); // lisa

可以进行参数的传递,但是不能函数复用。

ES6

使用super()关键字指代父类实例;

class Point(){
    constructor(x,y){
        this.x=x;
        this.y=y
    }
    print(){
        return this.x;
    }
}
class colorPoint extends Point(){
    constructor(x,y,color){
        super(x,y);
        this.x=x;
        this.y=y;
        this.color=color;
    }
}

ES5继承与ES6继承的区别:

ES5继承机制是先创建子类的实例对象,然后将父类的属性和方法添加到this上;

ES6继承机制是先创建父类的实例对象,在通过子类的构造函数修改this