Detection if a new keyword was used inside the constructor?

In a constructor object in JS, if it is created without a new keyword, the 'this' variable is a window reference instead of an object. Is it a particularly wise idea to try and discover it?

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()
+4
source share
2 answers

It is acceptable to propagate the 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];
    }
}
+8
source

I found this in SO, the last answer uses your approach;

Two ways, essentially the same thing under the hood. You can check what the scope of this is or you can check what this.constructor is.

, ;

, ?

.

Javascript Enlightment , , ;

, - "" , .

0

All Articles