组合继承
组合继承就是使用原型链实现对原型的属性和方法的继承,通过借用构造函数来实现对实例属性的继承。如:
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'
上期中借用构造函数遗留问题是:方法定义在构造函数中,方法无法复用。我们这起通过组合继承解决了这种问题,实现了方法复用。
原型式继承
原型式继承借助原型可以给予已有的对象创建新对象,同时还不必因此创建自定义类型。具体如下:
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
在object() 函数内部,先创建了一个临时性的构造函数,然后将传入的对象作为这个构造函数的原型,最后返回了这个临时类型的一个新实例。
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()函数,然后再根据具体需求对得到的对象加以修改即可。
ECMAScript 5 新增了object.create() 方法规范了原型继承,具体如下:
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 或留言,本人会在第一时间与您联系,谢谢!!
