组合继承就是使用原型链实现对原型的属性和方法的继承,经过借用构造函数来实现对实例属性的继承。如:前端
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.constructor = SubType;
SubType.prototype.sayAge = function() {
console.log(this.age)
}
var instance = new SubType('bill', 20);
instance.colors.push('black');
instance.colors // 'red', 'blue', 'green', 'black'
instance.sayName(); // 'bill'
var isntance2 = new SubType('bill2', 22);
instance2.colors // 'red', 'blue', 'green'
instance2.sayName(); // 'bill2'
复制代码
上期中借用构造函数遗留问题是:方法定义在构造函数中,方法没法复用。咱们这起经过组合继承解决了这种问题,实现了方法复用。bash
原型式继承借助原型能够给予已有的对象建立新对象,同时还没必要所以建立自定义类型。具体以下:函数
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
复制代码
在object() 函数内部,先建立了一个临时性的构造函数,而后将传入的对象做为这个构造函数的原型,最后返回了这个临时类型的一个新实例。ui
var persion = {
name: 'bill',
friends: ['one', 'two', 'three']
};
var anotherPersion = object(persion);
anotherPersion.name = 'bill2';
anotherPersion.friends.push('four');
var yetAnotherPersion = object(persion);
yetAnotherPersion.name = 'bill3'
yetAnotherPersion.friends.push('five');
persion.friends; // 'one', 'two', 'three', 'four', 'five'
复制代码
原型式继承要求必须有一个对象能够做为另外一个对象的基础。若是有这么一个对象的话,能够把它传递给object()函数,而后再根据具体需求对获得的对象加以修改便可。this
ECMAScript 5 新增了object.create() 方法规范了原型继承,具体以下:spa
var persion = {
name: 'bill',
friends: ['one', 'two', 'three']
};
var anotherPersion = object.create(persion);
anotherPersion.name = 'bill2';
anotherPersion.friends.push('four');
var yetAnotherPersion = object.create(persion);
yetAnotherPersion.name = 'bill3'
yetAnotherPersion.friends.push('five');
persion.friends; // 'one', 'two', 'three', 'four', 'five'
复制代码
若有侵权,请发邮箱至wk_daxiangmubu@163.com 或留言,本人会在第一时间与您联系,谢谢!! prototype