ES6 中的類

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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章