Detecting if the new keyword was used inside the constructor?

javascript, object

Solution

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];
    }
}

Problem

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() ```

Original source

Related problems