JS--继承

ES6之前的继承方法
基本思想:
1.1在子类的构造函数中通过call/apply借助父类的构造函数
1.2将子类的原型对象修改为父类的实例对象(即通过prototype和构造函数实现)

    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)
    console.log(stu);

ES6继承
基本思想:
通过extend关键字实现继承,子类可以继承父类中所有的方法和属性,子类必须在construc()方法中调用super()方法,因为新建的子类没有自己的this对象,而是继承了父类的this对象;

实质:利用extend关键字继承父类,然后继承父类的属性和方法

使用:

  • 解决代码的复用
  • 使用extends关键字实现继承
  • 子类可以继承父类中所有的方法和属性
  • 子类只能继承一个父类(单继承),一个父类可以有多个子类
  • 子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
  • 子类中如果有与父类相同的方法和属性,将会优先使用子类的(覆盖)
 class Person{
     constructor(myName, myAge){
         //this = stu
         this.name = myName; //stu.name = myName
         this.age = myAge; //stu.age = Age
     }
     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
     }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值