1 为什么super()
super是对父类构造器的调用。使用了后会自动继承父类的属性。要把super()放到第一行是因为了以防在super()之前,也就是没实例化父类之前,访问父类的属性。所以js将此作为一个语法点,必须这么写
2、为什么super(props)加props
如果不加props,又调用了父类的构造器,就没把属性值传给父类啊! 父类的属性都是undefined
class Fa {
name;
age;
constructor(props: { name: string; age?: number }) {
this.name = props.name;
this.age = props.age || 100;
}
}
class Son extends Fa {
color;
constructor(props: { name: string; age?: number; color: string }) {
super();
this.color = props.color;
}
}
const son = new Son({xxxx})
就会报错如下:
网上看到很多回答 说是:不加props 构造器里没法访问 this.props。我试了根本不是这样。而是直接报错如上图。props并不是类的一个 关键字!!所以 如果 父类、或子类 没有定义props属性。就根本没法 访问 this.props
————————
补充:
为什么很多资料都有如上图所示的回答 是因为,在react的Component类里对props就默认是从上层组件传过来的 参数。再react里默认props就是用来传参的方式。所以可以理解为this.props是react类组件必备的一个东西。普通的类是不必须需要的。
我们可以理解为 react 里对 props做了类似class Fa 的 下述处理(注意看注释)
class Fa {
name;
age;
props: any;//只有这里声明了 props
constructor(props: { name: string; age?: number }) {
this.name = props.name;
this.age = props.age || 100;
this.props = props;//这里给props赋值 下面才能用
}
getName() {
return this.name;
}
static staticFun() {
console.log("FA config ing");
}
}
Fa.staticFun();
const fa0 = new Fa({ name: "M" });
console.log("fa0.name", fa0.name);
console.log("fa0.fun", fa0.getName());
class Son extends Fa {
color;
constructor(props: { name: string; age?: number; color: string }) {
super(props);
this.color = props.color;
console.log("this.props", this.props);//这里才能用
}
logThis() {
console.log("this.props", this.props);//这里才能用
console.log("this", this);
}
}
const son0 = new Son({ name: "YANG", age: 10, color: "YELLOW" });
console.log("son0", son0);
console.log("son0.color", son0.color);