riju
riju

Reputation: 203

javascript: constructor function vs revealing module pattern for single use

I have come to understand that constructor functions can be instantiated to create new objects in javascript which has its own _proto_ property and also giving the property 'prototype' to the constructor function.

function MyController() {
    var controllerName = 'initialcontroller';
    function init() {
        console.log(controllerName);
    }
    this.init = init;
}

Here, init can be called like this:

var mycontroller = new MyController();
mycontroller.init();    

Supposing I am only instantiating only once and never again, isn't this an overkill if I don't intend to use all the prototype properties being provided by the MyController.prototype ?

Question: Instead, can i not code like this using the revealing module pattern?

var myController = function() {
    var controllerName = 'initialcontroller';
    function init() {
        console.log(controllerName);
    }
    return {
        init : init
    }
}();

Here, init can be called like this:

myController.init();

In this case, if I try to access any property inside myController that is not present, the javascript engine won't try to find whether the property exists anywhere in the prototype chain, thus saving my time.

Or is there any other advantages of instantiating a function that i am overlooking?

Upvotes: 3

Views: 1222

Answers (1)

defaude
defaude

Reputation: 308

If you simply want a "singleton"-like object with some methods and other properties, you could just use an object literal to simplify things even more:

var myController = {
    init: function (foo) {
        // do something with foo or whatever
    }
}

myController.init("bar");

Or - if you need some "private" internal state, use the regular revealing module pattern:

var myController = (function () {
    var internal = "i am private";
    return {
        init: function () {
            // blah blah
        }
    };
}());

myController.init();

About the prototype lookup time: Yeah, theoretically, the lookup traverses up the prototype chain when you're trying to access a non-existing property. Theoretically, this might be a tiny bit faster for plain ol' Object instances that have "no" specific constructor. In reality, this performance impact should be quite negligible. Don't attempt to optimize here unless you REALLY need it. :)

Upvotes: 2

Related Questions