ES6引入了class,其跟其它語言的class大致相同,JS中的class本質是function
它可以看做是語法糖
1.類的聲明
class name {
//...
}
2.類的定義
//匿名類
const a = class {
//...
}
//命名類
const b = class name {
//...
}
3.實例化
class name {
//...
}
const ex = new name();
注意
1️⃣ 函數存在函數提升,儘管類的本質是function,但是他沒有提升,在訪問類時必須要先聲明
2️⃣ 不可重複聲明
4.類的構造函數
類中的構造函數爲 constructor() 方法實現
class student {
constructor(name, classroom) {
this.name = name;
this.classroom = classroom;
}
}
const Tom = new student('Tom', '3年2班');
5.類的方法
如何在類中添加方法,如下所示:
class student {
constructor(name, classroom) {
this.name = name;
this.classroom = classroom;
} //注意這裏是沒有逗號的
info() {
console.log(`我叫${this.name},我是${this.classroom}的`);
}
}
const Tom = new student('Tom', '3年2班');
6.靜態方法
靜態方法是隻能由類調用的方法(就比如這裏只能用student調用而不是Tom),就好比 Array.form() 方法,它不能用於 [1, 2, 3].form() ,只能使用在原型上的方法
JS中使用 static 關鍵字定義靜態方法:
class student {
constructor(name, classroom) {
this.name = name;
this.classroom = classroom;
} //注意這裏是沒有逗號的
info() {
console.log(`我叫${this.name},我是${this.classroom}的`);
}
static description() {
console.log('student info');
}
}
const Tom = new student('Tom', '3年2班');
7.set()與get()方法
class student {
constructor(name, classroom) {
this.name = name;
this.classroom = classroom;
} //注意這裏是沒有逗號的
info() {
console.log(`我叫${this.name},我是${this.classroom}的`);
}
static description() {
console.log('student info');
}
set gradeInfo(value) {
this.grade = value;
}
get gradeInfo() {
return `grade is ${this.grade}`;
}
}
const Tom = new student('Tom', '3年2班');
8.類的繼承
先定義一個父類Animal:
class Animal {
constructor(name) {
this.name = name;
this.belly = [];
}
eat(food) {
this.belly.push(food);
}
}
繼承使用extends關鍵字:
class Dog extends Animal {
constructor(name) {
super();//必須寫在this前
this.name = name;
}
bark() {
console.log('汪汪汪!');
}
}
const dog = new Dog('dog');