JavaScript继承四部曲

四部曲:创建父类、创建子类、添加关系、修正子类原型

创建父类
function Human(name, age) {
    this.name = name;
    this.age = age;
}
Human.prototype.sayName = function(){ console.log(this.name); };
创建子类
function Woman(name, age, height) {
    Human.apply(this, arguments); //维持实例属性
    this.height = height;
}
添加关系
function F(){}
F.prototype = Human.prototype;
Woman.prototype = new F();
// 相当于
Woman.prototype = Object.create(Human.prototype);

修正子类原型

Woman.prototype.constructor = Woman;
Woman.prototype.sayHeight = function(){ console.log(this.height); };

你可能感兴趣的:(JavaScript继承四部曲)