给出一个简单的类
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在没有new关键字的情况下调用类构造函数?
用法应该允许
(new Foo("world")).hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
要么
Foo("world").hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
但后者失败了
Cannot call a class as a function
Run Code Online (Sandbox Code Playgroud)