- 基本使用 class的基本語法
使用class關(guān)鍵字定義一個類,本質(zhì)上是一個function,可以看做一個語法糖,定義了同一組對象(又稱為實例)共有的屬性和方法
構(gòu)造函數(shù)的prototype屬性也是存在的,實際上所有的方法都是綁定在prototype上面
在類的實例上調(diào)用方法就是在原型上的方法
constructor方法是類的默認(rèn)方法,通過new生成實例對象的時候就會被調(diào)用,一個類必須有constructor方法,如果沒有顯式定義,一個空的constructor就會被創(chuàng)建
類里面共有的屬性和方法必須要添加this使用
constructor 里面的 this 指向的是創(chuàng)建的實例對象
class Person {
constructor(x,y){
// constructor 里面的this 指向的是創(chuàng)建的實例對象
this.x = x
this.y = y
}
sum(){
console.log(this.x + this.y)
}
}
const user = new Person(5,5)
user.sum() // 10
- 類的繼承(extends和super關(guān)鍵字)
使用extends關(guān)鍵字可以繼承父類的方法,但是如果子類和父類中都存在同一個方法,會采取就近原則,調(diào)用子類的方法
class Father {
star(){
console.log("Father 中的 star 的方法")
}
sing() {
console.log("Father 中的 sing 方法")
}
}
class Son extends Father{
sing() {
console.log("Son 中的 sing 方法")
}
}
const user = new Son()
user.star() // Father 中的 star 的方法
user.sing() // Son 中的 sing 方法
如果想要傳遞參數(shù)需要使用super關(guān)鍵字,注意使用super關(guān)鍵字的時候必須寫在子類的this之前調(diào)用
constructor(x,y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y)
}
}
class Son extends Father{
constructor(x,y){
super(x,y)
this.x = x
this.y = y
}
}
const user = new Son(5,5)
user.sum() // 10