2025年ES6基础之——继承extends

ES6基础之——继承extends一个类可以去继承其他类里面的东西 这里定义一个叫 Person 的类 然后在 constructor 里面添加两个参数 name 和 birthday 下面再添加一个自定义的方法 intro 这个方法就是简单地返回 this name 和 this birthday class Person constructor name birthday this name name this

一个类可以去继承其他类里面的东西,这里定义一个叫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类里面定义的方法可以直接使用

编程小号
上一篇 2025-03-11 12:17
下一篇 2025-04-13 09:27

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/115750.html