Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if the new keyword was used inside the constructor?

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()
like image 920
Richard Avatar asked Feb 14 '23 13:02

Richard


1 Answers

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];
    }
}
like image 106
kennebec Avatar answered Feb 17 '23 01:02

kennebec