继承

2017-11-25  本文已影响0人  别让我一个人醉_1fa7
function Person(name, sex){
    this.name = name;
    this.sex = sex;
}

Person.prototype.printName = function(){
    console.log(this.name);
};

function Male(age){
    this.age = age;
}

Male.prototype.printAge = function(){
    console.log(this.age);
};

属性获取

改造一些Male

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

Male.prototype.printAge = function(){
    console.log(this.age);
};
实例化看看结果

var m = new Male('Byron', 'male', 26);
console.log(m.sex); // "male"

方法获取

-这样做需要注意一点就是对子类添加方法,必须在修改其prototype之后,如果在之前会被覆盖掉

Male.prototype.printAge = function(){
    console.log(this.age);
};

Male.prototype = Object.create(Person.prototype);
这样的话,printAge方法在赋值后就没了,因此得这么写

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

Male.prototype = Object.create(Person.prototype);

Male.prototype.printAge = function(){
    console.log(this.age);
};

最终方案

function inherit(superType, subType){
    var _prototype  = Object.create(superType.prototype);
    _prototype.constructor = subType;
    subType.prototype = _prototype;
}
使用方式

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

Person.prototype.printName = function(){
    console.log(this.name);
};    

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

// 在继承函数之后写自己的方法,否则会被覆盖
Male.prototype.printAge = function(){
    console.log(this.age);
};

var m = new Male('Byron', 'm', 26);
m.printName();

这样我们就在JavaScript中实现了继承

hasOwnProperty

m.hasOwnProperty('name'); // true
m.hasOwnProperty('printName'); // false
Male.prototype.hasOwnProperty('printAge'); // true
上一篇下一篇

猜你喜欢

热点阅读