Foo我在名为创建对象的 js 中有一个“类”(函数) 。由于它使用非常频繁,我希望它避免在new要创建它的新实例时要求使用键盘:Foo(something);而不是new Foo(something);.
我让它在 Firefox 中工作:
function Foo(arg) {
if (this instanceof Window)
return new Foo(arg);
//Object construction here.
this.bar = "Hello " + arg;
}
现在我可以通过将其作为函数调用来创建 Foo 的实例。
console.log(Foo("World").bar); //Output "Hello World" in console.
虽然这在 FF 中有效,但在 Chrome 中却没有,我还不敢测试 IE。
chrome 的问题是它window确实是DOMWindowchrome的类型
Uncaught ReferenceError: Window is not defined
并且this instanceof DOMWindow在 chrome 中不起作用,因为由于某种原因它给出了:
ReferenceError: DOMWindow is not defined
我也尝试过使用!(this instanceof Foo)并且typeof this似乎总是给予"object".
在所有浏览器上调用时,如何可靠地检测new关键字是否被省略?Foo
更新:!(this instanceof Foo)确实有效,我只是return this在我的实际Foo功能中迷路了。