在 JavaScript ES2015 中,在扩展类时,我们是否需要显式创建一个新的构造函数,或者我们可以只使用父类的构造函数?



我根据这篇 stackoverflow 帖子了解到,如果您想在子类中使用 this 并为其添加其他代码,我们需要调用super。 但是,如果没有其他事情,我们是否需要调用 make 一个新的构造函数并使用super

class SpecialCart extends Cart {
  // Is this constructor really necessary?
  constructor(name){
    super(name); 
  }
  // other methods go here....
}

不,如果你省略类中的构造函数,它将自动生成:

constructor( ) { } // for classes without `extends`
constructor(...args) { super(...args); } // for classes with `extends`

规范的相关部分可以在这里找到:

ClassTail ClassHeritage opt { ClassBodyopt}

如果

构造函数为空,则如果存在 ClassHeritage选择,则让构造函数成为解析源文本的结果constructor(... args){ super (...args);}

只需在支持类的环境中运行代码,就很容易测试:

class Base {
  constructor (x) {
    console.log('Base constructor called', x);
  }
}
class TestA extends Base {}
class TestB extends Base {
  constructor (x) {
    super(x);
  }
}
new TestA('a');
new TestB('b');

这将产生以下输出:

Base constructor called a
Base constructor called b

所以是的,当您不为继承类型指定构造函数时,将自动调用基的构造函数。当然,如果你想要一个不同的签名,或者想要执行一些其他任务,你必须为继承类型实现你自己的构造函数,然后还要进行super()调用,以便执行基的构造函数。

这也在规范中正式化:

  1. 如果构造函数为空,则,

    1. 如果存在 ClassHeritage选择,则

      1. 构造函数是解析源文本的结果

        constructor(... args){ super (...args);}
        

        使用带有目标符号方法定义的句法语法。

      1. 构造函数是解析源文本的结果

        constructor( ){ }
        

        使用带有目标符号方法定义的句法语法。

相关内容

最新更新