es6 class的实例化问题 new class extends XXX

今天看到monaco-editor源码中有这么一行代码:

WordDistance.None = new class extends WordDistance {
    distance() { return 0; }
};

很吃惊。
首先,找到这行代码是因为,bable编译时报错,未知的类型表达式 ClassExpression。我也是第一次看到直接在class定义前面加new 表达式的。
查阅es6与class相关的资料后,这种表达式是可行的,代表的时立即执行的类。但是我们都知道类型实例化时是需要在后面加()的。但是这里却没有,这也是我看不懂的原因之一。

理论上实例化过程:

class A {add(a,b){return a+b;}};
const c = new class extends A { constructor(name) {
    super();
    this.name = name;
  }}();
console.log(c); // 结果是
/*
{
name: undefined
    [[Prototype]]: A
    constructor: class extends
    length: 1
    name: ""
    prototype: A {constructor: ƒ}
    arguments: (...)
    caller: (...)
          [[FunctionLocation]]: VM503:1
          [[Prototype]]: class A
          [[Scopes]]: Scopes[2]
          [[Prototype]]: Object
}
*/
console.log(c.add(1,2)) // 结果是 3

经过实际验证,在类型实例化时,不加()确实也可以得到该类型的实例。确实很醉。
不加()的实例化:

class A {add(a,b){return a+b;}};
const c = new class extends A { constructor(name) {
    super();
    this.name = name;
  }};
console.log(c); // 结果是
/*
{
name: undefined
    [[Prototype]]: A
    constructor: class extends
    length: 1
    name: ""
    prototype: A {constructor: ƒ}
    arguments: (...)
    caller: (...)
          [[FunctionLocation]]: VM503:1
          [[Prototype]]: class A
          [[Scopes]]: Scopes[2]
          [[Prototype]]: Object
}
*/
console.log(c.add(1,2)) // 结果是 3

一摸一样。
所以结论是:js类型在实例化过程中,如果不需要传参数是可以省略()的。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容