大家好,又见面了,我是你们的朋友全栈君。
一个类可以去继承其他类里面的东西,这里定义一个叫Person的类,然后在constructor里面添加两个参数:name和birthday;
下面再添加一个自定义的方法intro,这个方法就是简单地返回this.name和this.birthday;
class Person{
constructor(name,birthday){
this.name = name;
this.birthday= birthday;
}
intro(){
return '${this.name},${this.birthday}';
}
}
然后再定一个Chef类,使用extends去继承Person这个类,如果这个类里面有constructor方法,就要在constructor方法里面使用super,它可以去调用父类里面的东西
class Chef extends Person{
constructor(name,birthday){
super(name,birthday);
}
}
let zhangsan = new Chef('zhangsan','1988-04-01');
console.log(zhangsan.intro()); //zhangsan,1988-04-01
因为Chef这个类继承了Person类,所以在Person类里面定义的方法可以直接使用
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154764.html原文链接:https://javaforall.cn