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()

你可能感兴趣的:(JavaScript)