JS继承的实现方式
首先声明一个父类
function Animal(name){ ??????????this.name =name || ‘Animal‘; ??????????this.sleep=function(){ ??????????????console.log(this.name +‘在睡觉呢~‘); ??????????} ??????} ??????Animal.prototype.eat=function(food){ ??????????console.log(this.name+‘正在吃‘+food); ??????}
1:构造函数的继承
function Dog(name){ ??????????Animal.call(this); ??????????this.name=name || ‘dog‘; ??????} ??????var dog =new Dog(); ??????console.log(dog);
对象dog继承了父类animal身上的属性和方法,不过属性相同,覆盖了父类的属性
特点: 1 :子类共享父类的属性和方法
2:可以向父类传递参数
缺点:子类只能继承父类的属性和方法但并不能继承父类的原型身上的属性和方法
2:原型链的继承
function Dog(name){ ????????this.name=name || ‘dog‘; ??????} ??????Dog.prototype=new Animal(); ??????var dog =new Dog(); ??????console.log(dog);
??????console.log(dog.constructor); ?//指向了Animal
/*
? Animal(name){
this.name =name || ‘Animal‘;
this.sleep=function(){
console.log(this.name +‘在睡觉呢~‘);
}
}
*/
特点:1:父类的属性和方法都能继承的到,包括父类原型身上的属性和方法也可以继承
2:简单,方便
缺点:1:创造子类实例时无法向父类传参
2:无法判断对象是子类实例化出来的还是父类实例化出来的。
3组合继承
function Dog(name){ ???????Animal.call(this); ???????this.name=name || ‘dog‘; ??????} ??????//Dog.prototype=new Animal(); //缺点在子类实力化的过程中父类函数执行了2次 ??????Dog.prototype = Object.create(Animal.prototype); ??????Dog.prototype.constructor=Dog; ??????var dog=new Dog(); ??????console.log(dog.constructor);/* ????? Dog(name){ ?????????Animal.call(this); ?????????this.name=name || ‘dog‘; ????}*/
第三种方案是目前比较完美的
JS学习之类的继承
原文地址:https://www.cnblogs.com/xubj/p/9987992.html