美文网首页
35 利用构造函数和原型对象实现继承

35 利用构造函数和原型对象实现继承

作者: CurryCoder | 来源:发表于2020-06-05 21:41 被阅读0次

    技术交流QQ群:1027579432,欢迎你的加入!

    欢迎关注我的微信公众号:CurryCoder的程序人生

    1.概述

    • ES6之前并没有给我们提供extends继承,我们可以通过构造函数+原型对象模拟实现继承,被称为组合继承

    2.call()

    • 作用:调用这个方法,可以调用这个函数并且修改函数运行时的this指向
    • 语法格式:
      函数名.call(thisArg, arg1, arg2, ...)
      
      • thisArg:当前调用函数this的指向对象;
      • arg1,arg2:传递的其他参数;

    3.借用构造函数继承父类属性

    • 核心原理:通过call()方法把父类的this指向子类的this,这样就可以实现子类继承父类的属性
      // 1.父构造函数
      function Father(uname, age){
          // this指向父构造函数的对象实例
          this.uname = uname;
          this.age = age;
      }
      // 子构造函数
      function Son(uname, age, score){
          // this指向子构造函数的对象实例
          Father.call(this, uname, age);  // 注意这句话!
          this.score = score;
      }
      
      var son  = new Son('刘德华', 18, 100);
      console.log(son);
      

    4.借用原型对象继承父类方法

    Son.prototype = Father.prototype错误的方法实现继承.png
    Son.prototype = new Father()正确的方法实现继承.png
    • 注意:如果利用对象的形式修改了原型对象,别忘了使用constructor指回原来的构造函数
      // 1.父构造函数
      function Father(uname, age){
          // this指向父构造函数的对象实例
          this.uname = uname;
          this.age = age;
      }
      
      Father.prototype.money = function(){
          console.log(888);
      }
      // 子构造函数
      function Son(uname, age, score){
          // this指向子构造函数的对象实例
          Father.call(this, uname, age);  // 注意这句话!
          this.score = score;
      }
      // Son.prototype = Father.prototype;这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着改变
      Son.prototype = new Father();  // 正确的方法
      // 如果利用对象的形式修改了原型对象,别忘了使用constructor指回原来的构造函数
      Son.prototype.constructor = Son;
      Son.prototype.exam = function(){
          console.log('这个是子构造函数专门的方法');
      }
      var son  = new Son('刘德华', 18, 100);
      console.log(son);
      console.log(Father.prototype);
      console.log(Son.prototype.constructor);
      

    5.资料下载

    相关文章

      网友评论

          本文标题:35 利用构造函数和原型对象实现继承

          本文链接:https://www.haomeiwen.com/subject/ckdzzhtx.html