javascript-site

Guaranteed Instantiation in Javascript

quick one today.

Let’s say you like the constructor pattern for objects. You probably do something similar to this:

function Person(name) {
    var __ = this;
    
    __.name = name;
    
    return __;
}

Let’s say you forget to use the”new” operator to instantiate the function and instead just call it as is while trying to assign it to a variable:

var mike = Person('Mike');
name = 'john';

console.log(mike.name) // results in john

The problem is “this”. Without referring to the “new” keyword, the function’s “this” refers to the global “this”. When you call the function, it can collide with any other variable in the global scope.

Of course you can fix it by doing:

var mike = new Person('Mike');
name = 'john';

console.log(mike.name) // results in mike

Of course, this is the right way to do it. But how can you make sure that even if the user doesn’t call it correctly, your class doesn’t create crazy collisions and potentially cause someone to spend hours debugging?

Easy! Check your object scope. Figure out who you belong to and force instantiation otherwise:

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

Now your object will return an instance of itself, even if called the wrong way.

var mike = Person('Mike');
name = 'john';

console.log(mike.name) // still results in Mike

Bye!

Leave a Reply

Your email address will not be published. Required fields are marked *