react的组件要super(props)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
1.调用super
的原因:在ES6中,在子类的constructor
中必须先调用super
才能引用this
;
2.super(props)
的目的:在constructor
中可以使用this.props
假设在es5要实现继承,首先定义一个父类:
//父类
function sup(name) {
this.name = name
}
//定义父类原型上的方法
sup.prototype.printName = function (){
console.log(this.name)
}
现在再定义他sup的子类,继承sup的属性和方法:
function sub(name,age){
sup.call(this,name) //调用call方法,继承sup超类属性
this.age = age
}
sub.prototype = new sup //把子类sub的原型对象指向父类的实例化对象,这样即可以继承父类sup原型对象上的属性和方法
sub.prototype.constructor = sub //这时会有个问题子类的constructor属性会指向sup,手动把constructor属性指向子类sub
//这时就可以在父类的基础上添加属性和方法了
sub.prototype.printAge = function (){
console.log(this.age)
}
这时调用父类生成一个实例化对象:
let jack = new sub('jack',20)
jack.printName() //输出 : jack
jack.printAge() //输出 : 20
这就是es5中实现继承的方法。
而在es6中实现继承:
class sup {
constructor(name) {
this.name = name
}
printName() {
console.log(this.name)
}
}
class sub extends sup{
constructor(name,age) {
super(name) // super代表的事父类的构造函数
this.age = age
}
printAge() {
console.log(this.age)
}
}
let jack = new sub('jack',20)
jack.printName() //输出 : jack
jack.printAge() //输出 : 20
对比es5和es6可以发现在es5实现继承,在es5中实现继承:
1.首先得先调用函数的call方法把父类的属性给继承过来;
2.通过new
关键字继承父类原型的对象上的方法和属性;
3.最后再通过手动指定constructor
属性指向子类对象
而在es6中实现继承,直接调用super(name)
,super
是代替的是父类的构造函数,super(name)
相当于sup.prototype.constructor.call(this, name)
.
子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
不忘初心,方得始终。