@windchimes
2019-03-19T02:25:38.000000Z
字数 1136
阅读 269
前端知识点总结
super是es6的语法糖,简化了继承的实现,实现了es5里的继承的三个步骤,此三步骤为
1)首先要调用函数的call方法把父类的属性继承过来
2)通过new关键字继承父类原型的对象上的方法和属性
3)手动指定constructor属性指向子类对象
//父类function sup(name) {this.name = name}//定义父类原型上的方法sup.prototype.printName = function (){console.log(this.name)}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() //输出 : jackjack.printAge() //输出 : 20
es6
class sup {constructor(name) {this.name = name}printName() {console.log(this.name)}}class sub extends sup{constructor(name,age) {super(name)this.age = age}printAge() {console.log(this.age)}}let jack = new sub('jack',20)jack.printName() //输出 : jackjack.printAge() //输出 : 20
react中的constructor中的super,如果用到了constructor就一定要写super,是用来初始化this的,可以绑定事件到this上;
如果在constructor中要使用this.props,则一定要给super传参数:super(props)
无论有没有constructor,在render中都是可以直接使用this.props的,这是react自动附带的;如果没用到constructor,是可以不写的