更新
在 node.js 和 deno 的情况下,您需要比较 withundefined而不是Window
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this === undefined) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe
原来的
TS 中的正确方法是使用类而不是prototype. 那么你不需要解决这个问题。
class Fool {
constructor(public name: string) {}
greet() {
console.log(`Fool greets ${this.name}`);
}
}
new Fool("Joe").greet(); // Fool greets Joe
如果你仍然想使用原型,不推荐的,你可以做一个修补程序:
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this.constructor === Window) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe