17.ES6继承

ES6之前的继承

  1. 在子类中通过call/apply方法借助父类的构造函数
  2. 将子类的原型对象设置为父类的实例对象
        function Person(myName, myAge) {
            this.name = myName;
            this.age = myAge;
        }
        Person.prototype.say =  function () {
            console.log(this.name, this.age);
        }
        function Student(myName, myAge, myScore) {
            // 1.在子类中通过call/apply方法借助父类的构造函数
            Person.call(this, myName, myAge);
            this.score = myScore;
            this.study = function () {
                console.log("day day up");
            }
        }
        // 2.将子类的原型对象设置为父类的实例对象
        Student.prototype = new Person();
        Student.prototype.constructor = Student;

        let stu = new Student("zs", 18, 99);
        stu.say();

ES6开始的继承:用extends和super

        1.在ES6中如何继承
        1.1在子类后面添加extends并指定父类的名称
     1.2在子类的constructor构造函数中通过super方法借助父类的构造函数

   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);
                super(myName, myAge);
                this.score = myScore;
            }
            study(){
                console.log("day day up");
            }
        }
        let stu = new Student("zs", 18, 98);
        stu.say();
  1. 在子类中通过call/apply方法借助父类的构造函数
    Person.call(this, myName, myAge);
  2. super(myName, myAge);这两句话等效的,或许Super是语法糖?
  3. super 调用父类的构造函数
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 简介 Class可以通过extends关键字实现继承。 上面代码定义了一个ColorPoint类,该类通过exte...
    oWSQo阅读 683评论 0 1
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,128评论 3 11
  • ES6之前的继承1. 在子类中通过call / apply方法借助父类的构造函数2. 将子类的原型函数设置为父类的...
    仰望_IT阅读 225评论 0 2
  • 继承6种套餐 参照红皮书,JS继承一共6种 1.原型链继承 核心思想:子类的原型指向父类的一个实例 Son.pro...
    灯不梨喵阅读 3,165评论 1 2
  • 简介 Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。...
    emmet7life阅读 361评论 0 0