相关疑难解决方法(0)

ES6:没有new关键字的调用类构造函数

给出一个简单的类

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)

javascript constructor instance ecmascript-6

71
推荐指数
7
解决办法
6万
查看次数

标签 统计

constructor ×1

ecmascript-6 ×1

instance ×1

javascript ×1