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


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

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*

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube