70-继承方式四-终极方案

  • 终极方案

    • 在子类的构造函数中通过 call 借助父类的构造函数

    • 将子类的原型对象修改为父类的实例对象

          function Person(myName, myAge) {
              // let per = new Object();
              // let this = per;
              // this = stu;
              this.name = myName; // stu.name = myName;
              this.age = myAge;   // stu.age = myAge;
      
              // this.say = function () {    // stu.say = function () {}
              //     console.log(this.name, this.age);
              // }
              // return this;
          }
      
          Person.prototype.say = function () {
              console.log(this.name, this.age);
          }
      
          function Student(myName, myAge, myScore) {
              // let stu = new Object();
              // let this = stu;
              Person.call(this, myName, myAge); // Person.call(stu);
              this.score = myScore;
              this.study = function () {
                  console.log("day day up");
              }
              // return this;
          }
      
          // 继承方式四就是把Student的原型对象改为Person实例对象
          Student.prototype = new Person();
          Student.prototype.constructor = Student;
          Student.prototype.run = function(){
              console.log("run");
          }
      
          let stu = new Student("ww", 19, 99);
          console.log(stu.score);  // 99
          stu.say();  // ww 19
          stu.study();  // day day up
      
      终极方案
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 将Student构造函数的原型对象改为Person构造函数的原型对象注意点: 要想使用Person原型对象中的属性...
    仰望_IT阅读 1,675评论 0 1
  • 在企业开发中, 如果构造函数和构造函数之间的关系是 is a 的关系, 那么就可以使用继承来优化代码, 来简化代码...
    仰望_IT阅读 1,220评论 0 1
  • ECMAScript简称就是ES,你可以把它看成是一套标准,JavaScript就是实施了这套标准的一门语言 现在...
    最美时光A阅读 2,870评论 0 0
  • 继承方式二的弊端如果动态的给Person的原型对象添加一个方法, 那么使用继承方式二就不能在子对象中访问say方法...
    仰望_IT阅读 1,432评论 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10

友情链接更多精彩内容