首页  >  文章  >  web前端  >  JavaScript 中可以不使用“new”关键字来调用类构造函数吗?

JavaScript 中可以不使用“new”关键字来调用类构造函数吗?

Barbara Streisand
Barbara Streisand原创
2024-10-26 04:12:27121浏览

 Can You Call a Class Constructor Without the 'new' Keyword in JavaScript?

调用不带“new”关键字的类构造函数

在 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>

直觉上,人们可能期望以下代码能够工作:

<code class="javascript">Foo("world").hello();       // "hello world"</code>

但是,此尝试失败,并出现错误“无法将类作为函数调用。”

类构造函数的角色

在 JavaScript 中,类定义了一个“类体”作为构造函数。当调用该类时,将调用该构造函数,创建该类的实例。因此,必须使用“new”关键字来启动构造函数并创建新对象。

省略“new”关键字:解决方案和权衡

主要有三种方法要克服此限制:

1.常规函数

除了使用类之外,我们还可以定义一个行为类似的常规函数​​。

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

2.强制使用“new”关键字

为了确保始终使用“new”关键字调用该类,可以在构造函数中实现一项检查:

<code class="javascript">class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) throw new Error("Class must be invoked with 'new'");
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}</code>

3.包装函数

通过将类包装在常规函数中,可以使用或不使用“new”关键字来调用它。

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

var _old = Foo;
Foo = function(...args) { return new _old(...args) };</code>

每个解决方案都有自己的权衡。常规函数缺乏类的封装和继承优势,而强制的“new”关键字可能会限制某些场景下的灵活性。包装函数方法在两个选项之间取得了平衡。

以上是JavaScript 中可以不使用“new”关键字来调用类构造函数吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

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