constructor和super

本文深入探讨JavaScript中的构造函数constructor及其默认行为,同时解析super关键字在ES6类继承中的双重用途,包括作为函数调用父类构造器及作为对象访问父类方法,并通过React示例说明super的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值