一、原型链继承
function Animal(name) {
//属性
this.name = name;
//方法
this.sleep = function () {
console.log(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);
实例可继承的属性有: 实例的构造函数的属性,父类构造函数的属性和父类原型的属性。
缺点:
1、新实例无法向父类构造函数传参。
2、继承单一
3、所有的新实例都会共享父类实例的属性。(原型上的属性是共享的,一个实例修改了原型属性,另一个实例的原型属性也会被修改)
二、构造函数继承
function Animal(name) {
this.name = name;
this.sleep = function () {
console.log(this.name + '正在睡觉');
}
}
Animal.prototype.eat = function (food) {
console.log(this.name + '正在吃' + food);
}
function Cat() {
Animal.call(this);
this.name = name || 'Tom'
}
重点: 使用call()或者apply()将父类构造函数引入子类函数
优点:
1、只继承了父类构造函数的属性,没有继承父类原型的属性。
2、解决了原型链继承的缺点。
3、可以继承多个构造函数属性。
4、在子实例中可向父实例传参。
缺点:
1、只能继承父类构造函数的属性,无法继承父类原型的属性。
2、无法实现构造函数的复用。(每次都要重新调用)
3、每个新实例都有父类构造函数的副本,臃肿。
三、组合继承
function Animal(name) {
this.name = name;
}
Animal.prototype.sayHi = function () {
console.log('我是' + this.name);
}
function Cat(name, age) {
Animal.apply(this, [name]);//第二次调用Animal()
this.age = age;
}
Cat.prototype = new Animal(); //第一次调用Animal()
var cat1 = new Cat('小咪', 1);
// var cat2 = new Cat('大咪', 2)
console.log(cat1.age); //1
cat1.sayHi(); //我是小咪
优点:
1、可以继承父类原型上的属性,可以传参,可复用。
2、每个新实例引入的构造函数属性是私有的。
缺点:
多次调用父类构造函数,子类的构造函数会替代原型上的那个父类构造函数。
四、原型式继承
function Animal(name) {
this.name = name;
this.sayHi = function () {
console.log('你好!我是' + this.name);
}
}
Animal.prototype.age = 2;
function Cat(name) {
let instance = new Animal();
instance.name = name || '小咪';
return instance;
}
var cat = new Cat();
console.log(cat.name); // 小咪
cat.sayHi(); //你好!我是小咪
重点:
用一个函数包装一个对象,然后返回这个函数的调用,这个函数就变成了可以随意增条属性的实例或对象。
缺点:
1、所有实例都会继承原型上的属性
2、无法实现复用。
五、Class继承
class Animal {
constructor(name = '小咪', age = 2) {
this.name = name;
this.age = age;
}
eat() {
console.log(this.name + 'eat food');
}
}
class Cat extends Animal {
constructor(name, age = 1) {
super(name, age); //继承父类属性
}
eat() {
super.eat(); //继承父类方法
}
}
let cat = new Cat();
cat.eat(); //小咪eat food
参考:https://segmentfault.com/a/1190000037460216