JavaScript/Inheritance

傳統形式:原型鏈 編輯

Grand.prototype.lastName = 'Ji';

function Grand() {

}
var grand = new Grand();

Father.prototype = grand;

function Father() {
    this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;

function Son() {

}
var son = new Son();

利用call或apply的非標準形式 編輯

function Person(name, age, sex) {
    this.name = name;
    this.sex = sex;
    this.age = age;
}

function Student(name, age, sex, grade) {
    Person.call(this, name, age, sex);
    this.grade = grade;
}
var person = new Student('qq', 18, 'M', 12);
console.log(person.name)

共享原型 編輯

Father.prototype.lastName = 'Deng';

function Father() {

}

function Son() {

}

function inherit(Target, Origin) {
        Target.prototype = Origin.prototype;
}

inherit(Son, Father);

Son.prototype.sex = 'male';
var son = new Son();
var father = new Father();

聖杯模式 編輯

在共享原型基礎上,另外加個構造函數 function F(){}當做中間層,然後讓 F 和 father 共有一個原型 F.prototype=father.prototype。然後 son.prototype = new F();使用原型鏈形成了繼承關係,現在改 son.prototype 就不會影響 father.prototype

function Father() {

}

function Son() {

}
Father.prototype.lastName = 'Deng';
function inherit(Target, Origin) {
    function F() {};
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    // 让子类的constructor重新指向自己,若不修改则会发现constructor指向的是父类的构造函数
    target.prototype.constructor = target;
}

inherit(Son, Father);
var son = new Son();
var father = new Father();