在 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()
最佳答案
当关键字被省略时强制一个新对象是相当常见的-
function Group(O){
if(!(this instanceof Group)) return new Group(O);
if(!O || typeof O!= 'object') O= {};
for(var p in O){
if(O.hasOwnProperty(p)) this[p]= O[p];
}
}
关于javascript - 检测构造函数中是否使用了 new 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250853/