ES6中的类

24 阅读1分钟

类的创建

es6中可以通过关键字class 创建类 :

class Person {
   name;
   constructor(name) {
       this.name = name;
   }
    intruduceSelf() {
        console.log(`my name is ${this.name}`)
    }
}

声明关键字constructor 会做几件事:

  • 创建一个新对象
  • 将this 绑定到这个新建的对象上,你可以在构造函数的代码中通过this来引用它。
  • 执行构造函数中的代码
  • 返回这个新对象

类的继承

与es5不同的是 es6有自己实现继承的简单方式,用不着像es5那样通过复杂的方式进行继承,而且有出错的可能,它是通过extends 关键字来实现的:

class Student extends Person {
    year;
    constructor(name,year) {
        super(name);
        this.year = year;
    }
}

需要说明的是 通过关键字extends继承后 如果子类有任何需要初始化的内容需要完成,它也必须使用 super()调用父类的构造器 ,并且传入父类构造函数期望的任何参数

封装

有时候我们需要让我们的数据私有化不对外暴露,所以我们需要将我们的保护起来 我们可以通过 #简写的方式实现


    class Student extends Person {
        #year; // 私有属性 通过# 来申明 方法也一样


        constructor(name, year) {
            super(name);
            this.#year = year;
        }

        intruduceSelf() {
            console.log(`My name is ${this.name} and i ma in year ${this.#year}`);
        }

        canStudyArchery () {
            return this.#year > 1
        }
    }