终于来到Class的章节了,Class是ES6所新增,在这之前都是使用Prototype去进行物件导向的方式,虽然Class本质上也还是Prototype也就是syntax sugar,但确实使撰写程式时方便许多
class Person{ constructor(name, age){ this.name = name, this.age = age } SayHi(){ console.log(this.name) }}class Student extends Person { constructor(name, age, grade, email) { super(name, age) this.grade = grade; this.email = email; } intro(){ console.log(`My name is ${this.name} grade is ${this.grade}`) }}const Nick = new Student("Nick", 22, "9", "text@gmailcom")console.log(Nick)
可以看到Prototype继承了Person类别,所以Class还是语法糖并不是像其他OOP语言一样
Static
顾名思义就是不会改变的,举圆周率因为不会变,所以把pi设定成Static确保是正确的数值
class Circle{ static pi = 3.14 constructor(radius){ this.radius = radius } areaFN(){ return this.radius * this.radius * Circle.pi }}const c = new Circle(10)console.log(c.areaFN()) //314