美文网首页
70-继承方式四-终极方案

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

作者: 仰望_IT | 来源:发表于2019-04-27 10:38 被阅读0次
  • 终极方案

    • 在子类的构造函数中通过 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
      
      终极方案

相关文章

网友评论

      本文标题:70-继承方式四-终极方案

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