In a constructor object in JS if it's created without the new keyword the 'this' variable is a reference to the window instead of the object. Is this a particularly wise idea to try and detect that?
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()
It is fairly common to force a new object when the keyword is omitted-
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With