JavaScript-继承方式

1.js中继承的终极方法
1.1在子类的构造函数中通过call借助父类的构造函数
1.2将子类的原型对象修改为父类的实例对象

    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;
      // return this;
    }
    Person.prototype.say = function () {
      console.log(this.name, this.age, this.score);
    }
    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.prototype = new Person();
    Person.prototype.constructor = Student;

 

ES6开始的继承方法

    class Person {
      constructor(myName,myAge) {
        // this = stu
        this.name = myName;  // stu.name = myName
        this.age = myAge;    // stu.age = myAge
      }
      say() {
        console.log(this.name, this.age);
      }
    }
    // 以下代码的含义:告诉浏览器将来Student这个类需要继承于Person这个类
    class Student extends Person {
      constructor(myName,myAge,myScore) {
        // 1.在子类中通过call/apply方法借助父类的构造函数
        // Person.call(this, myName,myAge);  // Person.call(stu)
        super(myName,myAge);
        this.score = myScore;
      }
      study() {
        console.log('day day up');
      }
    }
    let stu = new Student('zs',123,98);
    stu.say();

 

posted @ 2021-08-17 00:30  吃惊夜夜  阅读(37)  评论(0)    收藏  举报