给出一个简单的类
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在没有new关键字的情况下调用类构造函数?
用法应该允许
(new Foo("world")).hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
要么
Foo("world").hello(); // "hello world"
Run Code Online (Sandbox Code Playgroud)
但后者失败了
Cannot call a class as a function
Run Code Online (Sandbox Code Playgroud) 这是我想做的事情:
function a() {
// ...
}
function b() {
// Some magic, return a new object.
}
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
Run Code Online (Sandbox Code Playgroud)
可能吗?我可以通过挂钩到它的原型链b来成为一个a容易的实例a但是我必须这样做new b(),这就是我想要避免的.我想要的是什么?
更新:我觉得有可能明智地使用b.__proto__ = a.prototype.我下班后要去做更多的实验.
更新2:下面是你可以得到的最接近的,这对我来说已经足够了.谢谢所有有趣的答案.
function a() {
// ...
}
function b() {
if (!(this instanceof arguments.callee)) {
return new arguments.callee();
}
}
b.__proto__ = a.prototype …Run Code Online (Sandbox Code Playgroud)