class关键字创建
在class中使用extends关键字实现继承
语法:class子类extends父类{ }
//父类 可以看作其他子类共有的属性,也可以看作是构造函数中的 原型对象 class Person{ constructor(name,age){ this.name=name this.age=age } } class American extends Person{ } class Chinese extends Person{ } //在class类中,使用extends类关键字实现子类继承父类//语法:class 子类名称 extends 父类名称{ }//此时American 继承了Person中的属性。 const a1=new American('jack',12) console.log(a1) const b1= new Chinese('华为',30) console.log(b1) console.log('请开始你的表演')
(1)为什么在继承父类的子类中写constructor,一定要constructor 中调用super()
答案:因为,如果一个子类,通过entends关键字继承父类,那么在子类的constructor构造函数中,必须优先调用一下super() 代表父类的构造器,同时要传参需要写形参
(2)super()设个什么东西
答案:super是一个函数。而且,它是父类的构造器,子类中的super其实就是父类constructor构造器中的一个引用。
(3)为什么调用super()不传参数,父类中的值是undifine
因为调用super()相当于调用父类中的构造器,需要从子类中获取.
class American extends Person{
//先执行子类的构造器,并接收参数
constructor(name,age){
//在调用父类的构造器,并将参数穿过去
super(name,age)
}
}
const a1=new American('jack',18)
//父类 可以看作其他子类共有的属性,也可以看作是构造函数中的 原型对象 class Person{ constructor(name,age){ this.name=name this.age=age } say(){ console.log('大家好') } } class American extends Person{ constructor(name,age){ super(name,age) } } class Chinese extends Person{ constructor(name,age,idcard){ super(name,age) //在子类中, this只能放到super之后使用 this.idcard=idcard } } // //在class类中,使用extends类关键字实现子类继承父类 // //语法:class 子类名称 extends 父类名称{ } // //此时American 继承了Person中的属性。 const a1=new American('jack',12) console.log(a1) a1.say() const b1= new Chinese('华为',30,'12313243214321') console.log(b1) b1.say() console.log('请开始你的表演')