constructor和super

constructor

constructor是类的构造函数,经过new命令建立对象实例时,自动会掉用该方法 没有显式定义的状况下会被默认添加react

通常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关键字既能够当作函数来使用,也能够看成对象来使用ui

// 看成函数使用
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)this

// 当作对象使用
class Parent {
  name() {
    return 'name';
  }
}

class Child extends Parent {
  constructor() {
    super();
    console.log(super.name());
  }
}

let i = new Child(); // output name
复制代码

经过super调用父类的方法时,super会绑定子类的thisspa

React中super的使用

调用super的缘由:在ES6中,在子类的constructor中必须先调用super才能引用thisprototype

super(props)的目的:在constructor中可使用this.propscode

React文档建议,调用super时带上props,而关于React中无论是否是调用了super(pros)在render方法中都可以使用this.props的缘由则是React在对Class进行支持的时候不单单是添加了对ES6的支持还考虑了其余诸如ClojureScript、CoffeeScript的解决方案,详见 overreacted.io/why-do-reac…对象

相关文章
相关标签/搜索