在JS中的构造函数对象中,如果没有使用new关键字创建,则'this'变量是对窗口的引用而不是对象。这是一个特别明智的想法来尝试和检测?检测是否在构造函数中使用了新关键字?
function MyObject()
{
if (this === window) {
alert('[ERROR] Oopsy! You seem to have forgotten to use the "new" keyword.');
return;
}
// Continue with the constructor...
}
// Call the constructor without the new keyword
obj = MyObject()
可能重复的[如何检测函数是否被称为构造函数?](http://stackoverflow.com/questions/367768/how-to-detect-if-a-function-is-called- as-constructor) – Oriol
你的代码没有检测到像'var obj = MyObject.call(foo)' – Oriol
这样的东西对不起,你为什么要*要?描述文档中的首选用法,但最终由开发人员决定如何使用/实现对象。这就是编程/脚本编程的美妙之处。 – zamnuts