ES6:不使用 new 关键字调用类构造函数 [英] ES6: call class constructor without new keyword
问题描述
给定一个简单的类
class Foo {构造函数(x){if (!(this instanceof Foo)) 返回新的 Foo(x);this.x = x;}你好() {返回`你好 ${this.x}`;}}
是否可以在没有new
关键字的情况下调用类构造函数?
应允许使用
(new Foo("world")).hello();//你好世界"
或
Foo("world").hello();//你好世界"
但后者失败了
不能将类作为函数调用
类有一个类体",它是一个构造函数.
如果您使用内部 constructor()
函数,则该函数也将是相同的类主体,并且将是调用类时调用的函数,因此类始终是构造函数.>
构造函数需要使用 new
运算符来创建新实例,因此调用没有 new
运算符的类会导致错误,因为它是 需要类构造函数来创建新实例.
错误信息也很具体,正确
<块引用>TypeError: 类构造函数不能在没有 'new' 的情况下被调用
你可以;
- 使用常规函数代替类1.
- 始终使用
new
调用类. - 在常规包装函数中调用类,始终使用
new
,这样您就可以获得类的好处,但是仍然可以在使用和不使用new
操作符2.
1)
function Foo(x) {if (!(this instanceof Foo)) 返回新的 Foo(x);this.x = x;this.hello = 函数(){返回 this.x;}}
2)
class Foo {构造函数(x){this.x = x;}你好() {返回`你好 ${this.x}`;}}var _old = Foo;Foo = function(...args) { return new _old(...args) };
Given a simple class
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Is it possible to call the class constructor without the new
keyword?
Usage should allow
(new Foo("world")).hello(); // "hello world"
Or
Foo("world").hello(); // "hello world"
But the latter fails with
Cannot call a class as a function
Classes have a "class body" that is a constructor.
If you use an internal constructor()
function, that function would be the same class body as well, and would be what is called when the class is called, hence a class is always a constructor.
Constructors requires the use of the new
operator to create a new instance, as such invoking a class without the new
operator results in an error, as it's required for the class constructor to create a new instance.
The error message is also quite specific, and correct
TypeError: Class constructors cannot be invoked without 'new'
You could;
- either use a regular function instead of a class1.
- Always call the class with
new
. - Call the class inside a wrapping regular function, always using
new
, that way you get the benefits of classes, but the wrapping function can still be called with and without thenew
operator2.
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) };
这篇关于ES6:不使用 new 关键字调用类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!