JS-ES6 类
1. 如何定义一个类?
class Star{
} //定义了一个叫Star的类
let you = new Star(); // 实例化了一个Star类,并赋值给you
2. 类中的函数
构造函数:在创建类的实例的时候会自动执行的函数
class Star{
constrcutor(name,age){
// 这里的this是指向new出来的实例
this.name = name;
this.age = age;
console.log(this.name + "创建成功了!")
}
}
let person = new Star('handsome')
// 执行结果为 handsome创建成功
普通函数
class Star{
constrcutor(name,age){
// 这里的this是指向new出来的实例
this.name = name;
this.age = age;
}
// 定义一个方法
sayHi(){
console.log("你好鸭")
}
}
let person = new Star('Bob')
// 使用该方法
person.sayHi()
3.类的继承
关键字extends
class Son extends Father{
// 完全继承父类
}
子类调用父类
- 子类将数据传给父类
// 错误分析
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father{
constructor(x,y){
this.x = x
this.y = y
}
}
let son1 = new Son(2,3)
// 现在我要在子类里调用这个sum方法,但是并没有把x,y 传给父类,所以调用不了
son1.sum()
//正确示范
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
// 在将x,y赋值给实例的属性前,先用 super方法 把x,y传给父类,这样就可以调用父类的方法
super(x, y)
this.x = x
this.y = y
}
sub() {
console.log(this.x - this.y);
}
}
let son2 = new Son(2,3)
son2.sum()
// 输出5
-
子类调用父类的函数
子类中的函数遵循就近原则
- 子类的实例调用一个方法,先看子类中是不是有该方法,若有则直接调用
- 若没有,则在父类中查找这个方法
- 子类的实例调用一个方法,先看子类中是不是有该方法,若有则直接调用
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y);
}
say(){
console.log('你好鸭!')
}
}
class Son extends Father {
constructor(x, y) {
super(x, y)
this.x = x
this.y = y
}
sub() {
console.log(this.x - this.y);
}
say(){
super.say()
}
}
ES6 类 注意事项
- ES6里面的类没有变量提升,所以必须先实例化再使用
- 公用的属性必须 + this 否则类中找不到该属性
- 类中this的指向问题
- constructor 里面的this指向 创建的实例对象
- 方法里面的this指向这个方法的调用者