constructor
constructor
是类的构造函数,通过new
命令创建对象实例时,自动会掉用该方法 没有显式定义的情况下会被默认添加
一般constructor
方法返回实例对象this
,但也可以指定返回对象
function A() {
this.name = 'a';
this.age = 12;
}
const a = new A();
console.log(a.name, a.age); // a 12
function B() {
this.name = 'b';
this.age = 14;
return {
name: 'c',
age: 13
}
}
const b = new B();
console.log(b.name, b.age); // c 13
复制代码
super
super
关键字既可以当做函数来使用,也可以当作对象来使用
// 当作函数使用
class Parent {}
class Child extends Parent {
constructor() {
super();
}
}
复制代码
注:在constructor中必须调用super方法因为子类没有自己的this对象,而是继承父类的this对象,super就代表了父类的构造函数。super虽然代表了父类Parent的构造函数,但返回的是子类Child的实例,即super内部的this是指向Child,相当于Parent.prototype.constructor.call(this.proto)
// 当做对象使用
class Parent {
name() {
return 'name';
}
}
class Child extends Parent {
constructor() {
super();
console.log(super.name());
}
}
let i = new Child(); // output name
复制代码
通过super调用父类的方法时,super会绑定子类的this
React中super的使用
调用super的原因:在ES6中,在子类的constructor中必须先调用super才能引用this
super(props)的目的:在constructor中可以使用this.props
React文档建议,调用super时带上props,而关于React中不管是不是调用了super(pros)在render方法中均可以使用this.props的原因则是React在对Class进行支持的时候不仅仅是添加了对ES6的支持还考虑了其他诸如ClojureScript、CoffeeScript的解决方案,详见 overreacted.io/why-do-reac…