ES6快速入门——类与对象
1. 类
1.1 定义类
关键字:class
class People{ }
1.2 构造函数
关键字:constructor
说明:构造函数在对象创建的时候就会自动调用
class People {
constructor() { console.log('构造函数被调用了') }
}
1.3 属性与方法
1.3.1 属性
注意点:第一个this指向People实例,当然,此时的People还未创建实例,每个实例会独享一个内存空间,this就指向那个该实例的内存空间
class People {
constructor(name) {
this.name = name
}
}
1.3.1 方法
注意点:在类中声明一个方法是不用加function关键字的
class People {
constructor(name) {
this.name = name
}
eat(){
console.log(this.name,'正在吃东西...')
}
}
1.4 继承
关键字:extends
说明:Student继承People类后,也就是子类继承父类后,会有父类中的属性与方法
class Student extends People { }
1.5 重写
说明:父类中有方法eat() 子类中如果再写一个同名方法 eat() 那么字类中的同名方法将覆盖父类中的同名方法
注意点:构造函数也能被重写
class Student extends People {
eat(){
console.log('儿子在吃……')
}
}
1.6 super
说明:super能调用父类中的方法,调用方式为 super.functionName(),**super()**为调用父类构造函数
class Student extends People {
constructor(){
super(name)
}
eat(){
console.log('儿子在吃……')
}
}
2. 对象
2.1 创建实例
说明:定义People类后,用new即可创建一个实例对象
new People('My Name')
2.2 调用对象中的方法
let peo = new People('My Name')
peo.eat()