ES6 class类与类的继承
程序员文章站
2023-12-21 13:11:16
...
1.class类
class,定义一个类,前面不用加function关键字,直接把函数定义放进类里面即可,方法之间也不需要逗号分割
class Father {
constructor(){
this.name = 'xiaohua'
};
children(){
return `姓名:${this.name}`
}
}
let F = new Father()
console.log(F.children()); // 姓名:xiaohua
class 内部可以通过static来定义自己的 加粗样式 和 静态属性 ,该方法/属性不会被实例继承,不必使用new关键字,是直接通过类来调用,
如果使用new关键字调用属性,则会报undefined,如果调用方法,则会直接报错
class Father {
constructor(){
this.name = 'xiaohua'
};
static age = 18;
static children(){
return `姓名:二狗子`
}
}
console.log(Father.age); // 18
console.log(Father.children()); // 姓名:xiaohua
let F = new Father()
console.log(F.name); // xiaohua
console.log(F.age); // undefined
console.log(F.children()); // TypeError: F.children is not a function
2.class 继承
class继承时,需要试用extends关键字,子类必须在constructor方法中调用**super()**方法,否则会报错,因为子类没有自己的this对象,是继承父类的this对象,然后进行加工,如果不调用父类super方法,子类得不到this对象
class Father {
constructor(){
this.name = 'xiaoxin';
this.age = 5
}
getName(){
return `姓名:${this.name}`
}
}
class Son extends Father {
constructor(){
super() // 需要调用super() 如果不调用,直接报错.
};
getAge(){
return `年龄:${this.age}`
}
}
let s = new Son()
console.log(s.getName()); // 姓名:xiaoxin
console.log(s.getAge()); // 年龄:5