4种继承方式
- 原型式继承
- 给原型对象添加属性
- 原型替换
- 子类的原型对象替换为父类的原型对象
- 原型链继承
- 借用构造函数继承(经典式继承)
- 组合继承
1 原型式继承
给原型对象添加属性
- 只会继承原型对象中的属性
- 严格意义上不算是继承
function Person (name){
this.name = name;
}
Person.prototype.eat = function(){
console.log('eat');
}
var p1 = new Person('p1');
p1.eat(); // eat
原型替换
- 会丢失原来的原型对象上所有的成员
- 记得修正
constructor
的指向
function Person(name) {
this.name = name;
}
Person.prototype = {
constructor: Person, // 别忘记这个了!
eat: function(){
console.log('eat');
}
};
var p1 = new Person('p1');
p1.eat(); // eat
子类的原型对象替换为父类的原型对象
- 会丢失超类的实例属性
- 注意
constructor
的指向
function Animal () {
this.name = 'Animal';
}
Animal.prototype.info = 'des Animal';
function Person () {
this. name = 'Person';
}
Person.prototype = Animal.prototype;
Person.prototype.constructor = Person;
2 原型链继承
子类的原型方法替换为父类的实例
- 继承了父类的实例成员和原型对象成员
- 父类的实例成员会出现内存共享问题,因为是子类的原型对象,是公有成员
- 创建子类的实例时不能向父类传递参数
function Animal(){
this.name = 'Animal';
}
Animal.prototype.info = 'des Animal';
function Person(age){
this.age = age;
}
Person.prototype = new Animal();
Person.prototype.constructor = Person;
var p1 = new Person(18);
console.log(p1.name); // Animal
console.log(p1.info); // des Animal
console.log(p1.age); // 18
原型链继承缺陷示例代码:
function Animal(name){
this.name = name;
this.friends = ['zs', 'ls'];
}
Animal.prototype.info = 'des Animal';
function Person(age){
this.age = age;
}
Person.prototype = new Animal(); // 无法传递参数
Person.prototype.constructor = Person;
var p1 = new Person(18);
p1.friends.push('xm');
p1.__proto__.name = 'ww';
var p2 = new Person(22);
console.log(p2.friends); // zs ls xm
console.log(p2.name); // ww
3 借用构造函数继承(经典式继承)
借用apply和call方法实现继承
- 无法使用父类的原型
- 实例方法不可以重用
// 父类
function Animal (name) {
this.name = name;
this.logName = function () {
console.log(this.name);
}
}
// 子类
function Person (name){
Animal.call(this, name);
}
var p1 = new Person('p1');
console.log(p1); // Person {name: "p1", logName: function}
4 组合式继承
借用构造函数继承 + 原型式继承
- 借用构造函数继承解决实例成员的继承
- 原型式继承解决原型成员继承
// 父类
function Animal (name) {
this.name = name;
this.logName = function () {
console.log(this.name);
}
}
Animal.prototype = {
constructor: Animal,
logDes: function () {
console.log('des');
}
};
// 子类
function Person (name){
Animal.call(this, name);
}
Person.prototype = Animal.prototype;
Person.prototype.constructor = Person;
var p1 = new Person('p1');
console.log(p1);
网友评论