Guaranteed Instantiation in Javascript

quick one today.

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

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

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

[/pastacode]

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:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

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

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

[/pastacode]

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:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

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

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

[/pastacode]

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:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

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

[/pastacode]

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

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

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

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

[/pastacode]

Bye!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.