Class
在es6之前,是通过定义函数和函数的原型对象去实现类型
//before es6
function Person(name){
this.name = name
}
Person.prototype.say = function(){
console.log(`hi ${this.name}`)
}
//es6 定义一个Person类型
class Person{
constructor(name){ //构造函数
this.name = name
}
say(){
console.log(this.name)
}
}
静态成员
在我们类中的方法,分为实例方法和静态方法,实例方法需要实例对象进行调用,静态方法直接通过类型本身去调用。
es6新增static
关键字
class Person{
constructor(name){ //构造函数
this.name = name
}
say(){
console.log(this.name)
}
static create(name){
return new Person(name)
}
}
const tom = Person.create('tom')
类的继承
在es6之前是通过原型链去进行类的继承,在es6之后是通过extends进行类的继承
class Person{
constructor(name){ //构造函数
this.name = name
}
say(){
console.log(this.name)
}
}
class Student extends Person{
constructor(name,number){
super(name)
this.number = number
}
hello(){
super.say()//会调用父节点的方法
console.log('my school number is ${this.number}')
}
}
const s = new Student('jack','100')