ES6中加入了新特性class, 類實際上是個“特殊的函數”,就像你能夠定義的函數表達式和函數聲明一樣,類語法有兩個組成部分:類表達式和類聲明。
- 創建類class
class Animals {
constructor (name, action) {
this.name = name
this.action = action
}
speak () {
console.log(this.name + ' say hi!')
}
_action () {
console.log(this.name +' '+ this.action)
}
}
let dog = new Animals('Tom', 'is jump')
dog.speak()
dog._action()
- 繼承類extends
class Cat extends Animals {
constructor (name) {
super(name) // 超類繼承父類構造器, 並傳入參數name
}
speak () {
console.log(`我是${this.name}貓!`)
}
}
let cat = new Cat('Tom')
cat.speak()