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();