给定一个简单的类
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"
Or
Foo("world").hello(); // "hello world"
但后者失败了
Cannot call a class as a function
类有一个“类体”是一个构造函数.
如果您使用内部constructor()
函数,该函数也将是相同的类体,并且将是调用类时调用的函数,因此类始终是构造函数。
构造函数需要使用new
运算符创建一个新实例,因此调用一个没有new
运算符会导致错误,因为它是required用于类构造函数创建一个新实例。
错误信息也很具体,正确
类型错误:没有“new”就无法调用类构造函数
你可以:
- either use a regular function instead of a class1.
- 始终给班级打电话
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 the new
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) };
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)