1、super() :
(1)在calss中继承是通过extends关键字来实现的。子类必须在constructor()中调用super()方法,否则新建实例时会报错
(2)报错原因,是因为子类是没有自己的this对象的,它只能继承父类的this对象,然后对其进行加工,而super就是将父类中的this对象继承给子类,没有super,子类就得不到this对象
2、ES5与ES6关于继承的实现不同之处
(1)new操作符:
(1)首先生成一个空对象obj,并将其作为this
(2)将空对象的__proto__指向构造函数的prototype
(3)利用函数的call方法,将原本指向window的绑定对象this指向了obj(这样一来,当我们向函数中再传递实参时,对象的属性就会被挂载到obj)
(4)利用函数返回对象obj
(2)ES6与ES5关于继承
在ES5的继承中,先创建子类对象this,然后再将父类的方法添加到this上(Parten.apply(this))
在ES6的继承中,先创建父类的实例this(所以要调用super()方法,将父类的this对象继承给子类),之后,再用子类的构造函数修改this
3、super(props)------super()-----以及不写super的区别
如果你用到了constructor就必须写super(),是用来初始化this的,可以绑定事件到this上;
如果你在constructor中要使用this.props,就必须给super加参数:super(props);
(无论有没有constructor,在render中this.props都是可以使用的,这是React自动附带的;)
如果没用到constructor,是可以不写的;React会默认添加一个空的constructor。
Class A extends React.Component {
constructor(props) {
super(props)
this.props.s = 'hh'
this.props.x = = 0
this.state = {
user:'hhh',
age:'19'
}
}
}
4、super()用法
class A{
constructor(n){
console.log(n);
this.x = 100;
}
getX(){
console.log(this.x);
}
}
class B extends A{
constructor(){
super(100);
this.y = 200;
}
getY(){
console.log(this.y);
}
}
let f = new B();
f.getY()
f.getX()
class A {
constructor(name,color) {
this.name = name;
this.color = color;
}
toString() {
console.log('name:' + this.name + ',color:' + this.color);
}
}
class B extends A{
constructor() {
super('cat','white');
}
toString() {
console.log(super.toString());
}
}
var cat = new B()
cat.toString();