JS-13-ES6类和对象 / ES6继承

一、ES6类和对象

1.从ES6开始系统提供了一个名称叫做class的关键字, 这个关键字就是专门用于定义类的;

        class Person{
            // 当我们通过new创建对象的时候, 系统会自动调用constructor
            // constructor我们称之为构造函数
            constructor(myName, myAge){
                this.name = myName;
                this.age = myAge;
            }
            // 实例属性
            // name = "lnj";
            // age = 34;
            // 实例方法
            say(){
                console.log(this.name, this.age);
            }
            // 静态属性
            static num = 666;
            // 静态方法
            static run() {
                console.log("run");
            }
        }
        // let p = new Person();
        let p = new Person("zs", 18);
        p.say();
        console.log(Person.num);
        Person.run();

二、JavaScript-ES6继承

ES6之前的继承:
1.在子类中通过call/apply方法借助父类的构造函数;
2.将子类的原型对象设置为父类的实例对象;

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

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

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();

-End

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值