继承
子类共享父类的属性和方法,js的继承都是基于原型实现的
定义一个父类
function Animal (name) {
// 属性
this.name = name;
// 实例方法
this.say= function(){
console.log("My name is "+this.name);
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
原型链继承:子类的原型指向父类的实例
//子类
function Cat(){}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
//子类实例
var cat = new Cat();
console.log(cat.name);//cat
cat.say();//My name is cat
cat.eat('fish');//cat正在吃:fish
优点
- 非常纯粹的继承关系,实例是子类的实例,也是父类的实例
- 父类新增原型方法/原型属性,子类都能访问到
- 简单,易于实现
缺点 - 要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
- 无法实现多继承
- 来自原型对象的引用属性是所有实例共享的
- 创建子类实例时,无法向构造函数传参
构造继承(call、apply继承)
组合继承(原型链和构造继承的组合)
function Cat(name){
Animal.call(this,name);
}
//子类原型调用父类构造函数
//此时Cat.prototype中的constructor被重写了,即Cat.prototype === Animal
Cat.prototype = new Animal();
//使Cat.prototype指回Cat本身
Cat.prototype.constructor = Cat;
// 子类实例调用父类构造函数
var cat = new Cat("cat");
console.log(cat.name);//cat
cat.say();//My name is cat
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
优点
- 可以继承实例属性/方法,也可以继承原型属性/方法
- 既是子类的实例,也是父类的实例
- 不存在引用属性共享问题
- 可传参
- 函数可复用
缺点
- 调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)
ES6继承(语法糖)
super
class Animal{
constructor(name){
this.name = name;
}
say(){
console.log("My name is "+this.name);
}
eat(food){
console.log(this.name+" is eating "+food);
}
}
class Cat extends Animal{
constructor(name){
//必须要super关键字才能成功继承!!
super(name);
}
}
var tom = new Cat("Tom");
tom.say();
tom.eat("apple");
console.log(tom instanceof Animal); // true
console.log(tom instanceof Cat); //true
优点完美
寄生组合继承
function Cat(name){
Animal.call(this);
this.name = name;
}
(function(){
// 创建一个没有实例方法的类
var Super = function(){};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
})();
// Test Code
var cat = new Cat();
console.log(cat.name);
cat.say();
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
优点完美
缺点不懂