前言
Js作为面向对象的弱类型语言,继承也是其非常强大的特性之一
JS继承的实现方式
既然要实现继承,那么首先我们得有一个负累,代码如下:
function Animal() {
this.name = name || 'Animal'
this.features = []
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 cat1 = new Cat()
var cat2 = new Cat()
console.log(cat1.name)
console.log(cat1.eat('fish'))
console.log(cat1.sleep())
console.log(cat1 instanceof Cat) // true
console.log(cat1 instanceof Animal) // true
cat2.features[0] = 'a'
console.log(cat1 features) // ['a']
console.log(cat2 features) // ['a']
特点:
- 非常纯粹的继承关系,实例是子类的实例,也是父类的实例
- 父类新增方法/原型属性,子类都能访问到
- 简单,易于实现
缺点:
- 如果要新增原型方法和属性,则必须放在new Animal()之后执行
- 无法实现多继承
- 来自原型对象的多有属性被所有实例共享
- 创建子类实例时,无法向父类构造函数传参
构造函数
function Cat() {
Animal.call(this)
this.name = name || 'Cat'
}
var cat = new Cat()
console.log(cat.name) // Cat
console.log(cat.sleep())
console.log(cat instanceof Cat) // true
console.log(cat instanceof Animal) // false
console.log(cat.eat) // undefinded 无法继承原型方法
特点:
- 解决了原型链继承中的 子类实例共享父类引用属性的问题
- 创建子类实例时,可以向父类传递参数
- 可以实现多继承(call多个父类对象)
缺点:
- 实例并不是父类的实例,只是子类的实例
- 只能继承父类的实例属性和方法,不能继承原型属性和方法
- 无法实现函数的复用,每个子类都有子类实例函数的副本,影响性能
实例继承
function Cat(name) {
var instance = new Animal()
instance.name = name || 'name'
return instance
}
var cat = new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Cat) // false
console.log(cat instcneof Animal) // true
特性:
- 不限制调用方式,不管 new Cat() 还是 Cat() 返回的对象具有相同的效果
缺点:
- 实例时父类的实例而非子类的实例
- 不支持多继承
拷贝继承
function Cat(name) {
var animal = new Animal()
for (let i in animal) {
Cat.prototype[i] = animal[i]
}
this.name = name
}
var cat = new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Cat) // true
console.log(cat instcneof Animal) // false
特点:
- 支持多继承
缺点:
- 效率低,内存占用高(因为要拷贝父类属性)
- 无法获取父类不可枚举的方法(不可枚举的方法不能在for in中访问)
组合继承
function Cat(name) {
Aimal.call(this)
this.name = name
}
Cat.prototype = new Animal()
var cat = new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Cat) // true
console.log(cat instcneof Animal) // true
特点:
- 可以继承实例属性和方法,也可继承原型属性和方法
- 即使子类实例也是父类实例
- 不存在引用属性共享的问题
- 函数可复用
缺点:
- 调用里两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份隔离了)
寄生组合继承
function Cat(name) {
Animal.call(this)
this.name = name
}
(() => {
function Fn() {}
Fn.prototype = Animal.prototype
Cat.prototype = new Fn()
})();
var cat = new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Cat) // true
console.log(cat instanceof Animal) // true
寄生组合继承时继承的最佳实现方式