一個類可以去繼承其他類里面的東西,這里定義一個叫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類里面定義的方法可以直接使用