Code of the Day: Javascript, create object without calling new on the Constructor

Here’s a simple trick to avoid having to call new on a constructor. All you have to do is have the constructor do it for you. Here’s how.

Check if the `this` variable is an instanceof of the Constructor. If not, then return a new instance of the constructor whiling passing the same arguments. `new ConstructorName(arg1, arg2, … argN)`.

If you call a constructor without using this trick, `this` will be referenced to the scope to which the constructor is contained within. Which in most cases is `window`.

Example:

var Person = function( name ){
    if(!(this instanceof Person)){
        return new Person(name);
    }
    this.name = name || "NA" ;
    return this;
};

Live Demo:*click the results tab*

(Page view Count: 27)