首页  >  文章  >  web前端  >  如何在没有“new”关键字的情况下调用 ES6 类构造函数?

如何在没有“new”关键字的情况下调用 ES6 类构造函数?

Patricia Arquette
Patricia Arquette原创
2024-10-26 02:27:27535浏览

How Can I Call an ES6 Class Constructor Without the

在没有“new”的情况下调用 ES6 类构造函数

在 ES6 中,类是构造函数的语法糖。当不使用 new 关键字调用类时,它不会创建该类的新实例。相反,它直接调用类的构造函数。

考虑以下类:

<code class="javascript">class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}</code>

如果我们尝试在不使用 new 关键字的情况下调用此类,则会收到错误:

Cannot call a class as a function

这是因为类构造函数旨在创建类的新实例。不使用 new 运算符调用它们相当于调用常规函数。

为了允许在不使用 new 关键字的情况下调用类构造函数,我们可以使用构造函数和箭头函数的组合,如下所示:

<code class="javascript">class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}

const FooWithoutNew = () => new Foo(...arguments);</code>

现在,我们可以使用 FooWithoutNew 来调用不带 new 关键字的类构造函数:

FooWithoutNew("world").hello(); // "hello world"

但是,需要注意的是,这种方法有一些缺点。首先,它需要创建一个单独的函数,这可能很不方便。其次,它破坏了构造函数返回新实例的行为。

一般情况下,为了清晰和一致性,建议始终使用 new 关键字调用类构造函数。

以上是如何在没有“new”关键字的情况下调用 ES6 类构造函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn