今天看到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类型在实例化过程中,如果不需要传参数是可以省略()的。