JS 常用继承

原文出处:爱睡觉的小猫咪

1.原型链继承

function SuperType() {
    this.property=true;
}
SuperType.prototype.getSuperValue=function () {
    return this.property;
};
function SubType() {
    this.subproperty=false;
};
SubType.prototype=new SuperType();
SubType.prototype.getSubValue=function () {
    return this.subproperty;
}
var instance=new SubType();

2.构造函数继承

function SuperType(name) {
    this.name=name;
}
function SubType() {
    SuperType.call(this,'Nicholas');
    this.age=29;
}
var instance=new SubType();
console.log(instance.name+' '+instance.age);//Nicholas 29

3.组合继承

function SuperType(name) {
    this.name=name;
    this.colors=['red','blue','green']
}
SuperType.prototype.sayName=function () {
    console.log(this.name);
}
function SubType(name,age) {
    SuperType.call(this,name);
    this.age=age;
}
SubType.prototype=new SuperType();
SubType.prototype.sayAge=function () {
    console.log(this.age);
}
var instance1=new SubType('Nicholas',29);
instance1.colors.push('black');
console.log(instance1.colors);
instance1.sayName();
instance1.sayAge();
var instance2=new SubType('Greg',27);
console.log(instance2.colors);
instance2.sayName();
instance2.sayAge();

4.组合寄生继承

//将组合继承中的实例化继承:
//SubType.prototype=new SuperType();
//改为浅拷贝继承:

function Object.create(o){
    function F() {};
    F.prototype=o;
    return new F();
}

function inheritPrototype(subType,superType){
    var prototype=Object.create(superType.prototype);//创建对象
    prototype.constructor=subType;
    subType.prototype=prototype;
}
inheritPrototype(SubType,SuperType);
posted @ 2018-06-08 13:25  叙帝利  阅读(111)  评论(0)    收藏  举报