終於來到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語言一樣
顧名思義就是不會改變的,舉圓周率因為不會變,所以把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