gpt4 book ai didi

javascript - ES6 : call class constructor without new keyword

转载 作者:IT王子 更新时间:2023-10-29 02:52:05 24 4
gpt4 key购买 nike

给定一个简单的类

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

是否可以在不使用 new 关键字的情况下调用类构造函数?

使用应该允许

(new Foo("world")).hello(); // "hello world"

或者

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

但后者失败了

Cannot call a class as a function

最佳答案

类有一个“类体”,是一个构造函数
如果您使用内部 constructor() 函数,该函数也将是同一个类主体,并且将是调用类时调用的函数,因此类始终是构造函数。

构造函数需要使用 new 运算符来创建新实例,因此调用没有 new 运算符的类会导致错误,因为它是 类构造函数需要来创建新实例。

错误信息也很具体,而且正确

TypeError: Class constructors cannot be invoked without 'new'

你可以;

  • 要么使用常规函数代替类1
  • 始终使用 new 调用类。
  • 在包装常规函数中调用类,始终使用 new,这样您可以获得类的好处,但是包装函数仍然可以在有和没有 new 运算符2

1)

function Foo(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
this.hello = function() {
return this.x;
}
}

2)

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

var _old = Foo;
Foo = function(...args) { return new _old(...args) };

关于javascript - ES6 : call class constructor without new keyword,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com