要实现继承,必须要有一个父类
//定义一个动物类
function Animal(name){
//属性
this.name = name;
//实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉');
}
}
//原型方法
Animal.prototype.eat = function(food){
console.log(this.name + '正在吃' + food);
}
复制代码
1.原型链继承
核心 将父类的实例作为子类的原型
function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.name); //cat
console.log(cat.eat('fish')); //cat正在吃fish
console.log(cat.sleep()); //cat正在睡觉
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
复制代码
特点:简单易于实现,父类的新增的实例与属性子类都能访问
缺点:可以在子类中增加实例属性,如果要新增加原型属性和方法需要在new父类构造函数的后面 ,无法实现多继承 , 创建子类实例的时候,不能向父类构造函数中传参
2.构造继承
核心 使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类
function Cat(name){
Animal.call(this,'cat');
}
let cat = new Cat();
console.log(cat.name); //cat
console.log(cat.sleep()); //cat正在睡觉
console.log(cat instanceof Animal); //false
console.log(cat instanceof Cat); //true
复制代码
特点:解决了子类构造函数向父类构造函数中传递参数,可以实现多继承(call或者apply多个父类)
缺点:方法都在构造函数中定义,无法复用。不能继承原型属性、方法,只能继承父类的实例属性和方法
3.实例继承
核心:为父类实例添加新特性,作为子实例返回
function Cat(name){
var instance = new Animal(name);
return instance;
}
var cat = new Cat('cat');
console.log(cat.name); //Tom
console.log(cat.sleep()); //Tom正在睡觉
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //false
复制代码
特点:不限制调用方式,简单易实现
缺点:不能多次继承
4.拷贝继承
function Cat(name){
var animal = new Animal();
for(var key in animal){
Cat.prototype[key] = animal[key];
}
//如果使用prototye.name = name;会出现所有实例的name都是相同的,不能设置到原型上
this.name = name;
}
复制代码
优点:支持多继承
缺点:效率低,内存占用高 , 无法获取父类不可枚举的方法
5.组合继承
核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
function Cat(name){
Animal.call(this,name);
}
Cat.prototype = new Animal();
//组合继承需要修复构造函数的指向
Cat.prototype.constructor = 'Cat'
复制代码
优点:既可以继承属性,也可以继承方法。既是子类的实例,也是父类的实例。不存在引用属性共享的问题。可传参。函数可复用
6.寄生组合继承
核心:通过寄生的形式,砍掉父元素的实例属性,这样在调用两次父类的构造的时候,就不会初始化两次实例方法和属性,避免了组合继承的缺点
function Cat(name){
Animal.call(this,name);
}
(function(){
//创建一个没有实例方法的类
var Super = function(){}
Super.prototype = Animal.prototype;
Cat.prototype = new Super();
})()
//寄生组合继承需要修复构造函数的指向
Cat.prototype.constructor = 'Cat';
var cat = new Cat('cat');
复制代码
优点:堪称完美
缺点:实现较为复杂
es6继承
//class 相当于es5中的构造函数
class People{
constructor(name='wang',age='27'){
this.name = name;
this.age = age;
}
eat(){
console.log(`${this.name} eat food`);
}
}
//继承父类
class Woman extends People{
constructor(name='ren',age='27'){
super(name,age);
}
eat(){
super.eat()
}
}
let womanObj = new Woman('xiaoxiami');
womanObj.eat();
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END