您的位置:首页 > 其它

组合继承 和 原型式继承、寄生组合式继承

2014-08-28 00:00 344 查看
摘要: 组合继承(combination inheritance 经典继承):(原型链、借用构造函数[constructor stealing]) 使用“原型链”实现对原型属性和方法的继承(实现了函数复用),通过“借用构造函数”实现对实例属性的继承(保证每个实例都有自己的属性);
原型式继承(Prototypal Inheritance):借助原型可以基于已有对象创建新对象

//以下代码均摘自 Nicholas C.Zakas《Professional JavaScript for Web Developers》
//组合继承实例代码:

function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
//通过call()调用SuperType的构造函数,继承SuperType属性
SuperType.call(this, name);                 //第二次调用SuperType()
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
console.log(this.age);
};
var instancel = new SubType("Nicholas", 12);    //第一次调用SuperType()
instancel.colors.push("black");
console.log(instancel.colors);    //"red,blue,green,black"
instancel.sayName();              //"nicholas"
instancel.sayAge();               //12

var instancel2 = new SubType("Tom", 11);
console.log(instancel2.colors);   //"red,blue,green"
instancel2.sayName();             //"Tom"
instancel2.sayAge();              //11


//原型式继承实例代码:
function createObj(o) {//对传入的对象执行了一次浅复制
function F() {}
F.prototype = o;
return new F();
}
var person = {
name: "Tom",
friends: ["one", "two", "van"]
};
var huPs = createObj(person);
huPs.name = "GRE";
huPs.friends.push("Rob");

var yePs = createObj(person);
yePs.name = "Lin";
yePs.friends.push("Sari");

console.log(person.friends);//"one,two,van,Rob,Sari"

/*
var huPs = Object.create(person);
var yePs = Object.create(person, {
name: {
value: "Greg"
}
});
第二个参数与Object.defineProperties()方法的第二个参数格式相同,每个属性都是通过自己
的描述符定义,以这种方式指定的任何属性都会覆盖原型对象上的同名属性
*/

3ff8 class="brush:js;toolbar: true; auto-links: false;">
/*
寄生组合式继承:通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型的原型的一个副本。使用寄生式继承来继承超类型的原型,然后将结果指定给子类型的原型
*/
//接收两个参数:子类型构造函数、超类型构造函数
function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype);    //创建对象 超类型原型副本
prototype.constructor = subType;                //增强对象 为副本增添construct属性
subType.prototype = prototype;                  //指定对象
}
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;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
console.log(this.age);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐