首页 > 技术文章 > 怎样实现构造函数的继承

aisowe 2019-10-14 20:21 原文

封装/继承/多态是面向对象编程的三个特征, js中实现构造函数的继承需要分两步实现: 

1. 在子类构造函数中调用父类的构造函数;

2. 让子类的原型对象"复制"父类的原型对象;

下面是一个具体的例子: 

function Father(name){
    this.name = name;
}

function Son(name, age){
    Father.call(this, name);
    this.age = age;
}
Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son;

var lilei = new Son("Lilei", 23);
lilei.name; // "Lilei"
lilei.age; // 23
lilei.constructor === Son; // true

 

推荐阅读