当前位置:   article > 正文

javascript 常见的继承方式

javascript 常见的继承方式

继承是基于“类”的,在没有es6前,一个用来new的函数就充当了“类”的构造函数构造函数的prototype上面的属性就等于实例的共享属性。

这篇文章主要记录使用函数实现常见的2种继承方式,理解了这2种继承方式,其他的都不再难理解了

1.原型链继承

  1. function Parent(name){
  2. this.name=name;
  3. }
  4. Parent.prototype.myname=function(){
  5. console.log("name:"+this.name)
  6. }
  7. function Child(){}
  8. //直接引用
  9. Child.prototype=Parent.prototype;
  10. var child=new Child("小明");
  11. console.log("child",child)
  12. child.myname();//undefined
优点:

直接引用,Parent的prototype属性变化时候也会被变化

弊端:

无法调用“父类”的构造函数,导致无法初始化实例属性

2.构造函数继承

  1. function Parent(name){
  2. this.name=name;
  3. }
  4. Parent.prototype.myname=function(){
  5. console.log("name:"+this.name)
  6. }
  7. function Child(...arg){
  8. //直接牵复制
  9. Parent.call(this,...arg)
  10. }
  11. var child=new Child("小明");
  12. console.log("child",child.name)
弊端:

无法继承父类的prototype方法

3.组合模式

结合原型链和构造函数继承的优点

  1. function Parent(name){
  2. this.name=name;
  3. }
  4. Parent.prototype.myname=function(){
  5. console.log("name:"+this.name)
  6. }
  7. function Child(...arg){
  8. //直接牵复制
  9. Parent.call(this,...arg)
  10. }
  11. Child.prototype=Parent.prototype;
  12. var child=new Child("小明");
  13. console.log("child",child)
  14. child.myname();


4.es6 的class extends
 

参考:extends - JavaScript | MDN


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/41367
推荐阅读
相关标签
  

闽ICP备14008679号