首页  >  文章  >  web前端  >  ES6 中可以调用没有“new”的类构造函数吗?

ES6 中可以调用没有“new”的类构造函数吗?

Susan Sarandon
Susan Sarandon原创
2024-10-26 01:55:02295浏览

 Can You Call a Class Constructor Without 'new' in ES6?

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

给定类定义:

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

这是不可能的不使用 new 关键字直接调用类构造函数。这是因为 ES6 中的类本质上有一个构造函数,该函数在调用该类时会被调用。

调用没有 new 的类会导致错误:

Cannot call a class as a function

此错误消息清楚地表明类构造函数只能使用 new 运算符调用,这是创建类的新实例所必需的。

要克服此限制,请考虑以下方法:

  • 使用常规函数:
function Foo(x) {
  this.x = x;
  this.hello = function() {
    return `hello ${this.x}`;
  }
}
  • 始终使用 new 调用类:
(new Foo("world")).hello(); // "hello world"
  • 将类包装在函数中并使用 new 调用:
var FooWrapper = function(...args) { return new Foo(...args) };
FooWrapper("world").hello(); // "hello world"

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

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