0

While working on maintainence of a site, I came across this coding pattern being followed for all the javascript files included in the page, which seems like a mix of factory pattern and some other pattern:

var MainFunction = new function() {
    var _cntr = 0;
    var _sCntr = 0;
    var _init = function() {
        //main logic & other methods called here
        _innterMethod1();
        _innterMethod2();
    }
    var _innerMethod1 = function() {
        // innermethod1 logic goes here
    }
    var _innerMethod2 = function() {
        // innermethod2 logic goes here
    }
    this.tostring = function() {
        return "[object MainFunction]";
    };
    _init.call(this);
};

While it is easy to understand the flow, what is bothering me is what pattern is being followed here? What is the author trying to acheive/gain with this style of coding [ compared to following other more popular patterns to achieve the same functionality?]

guacamole
  • 297
  • 5
  • 16
  • 1
    possible duplicate of [\`new function()\` with lower case "f" in JavaScript](http://stackoverflow.com/questions/2274695/new-function-with-lower-case-f-in-javascript) – Qantas 94 Heavy Aug 19 '14 at 10:54
  • Agreed the same technique is being used in the above mentioned question. But I would like to know what is the purpose of **this.tostring** used in the technique above? Does it change the way code is being executed in any way? Also, is this a preferrable approach for code that has to be executed only once? – guacamole Aug 19 '14 at 11:20
  • See [Is it right to think of a Javascript Function Expression that uses the 'new' keyword as 'static'](http://stackoverflow.com/q/10406552/1048572) on why this pattern [**should not be used**](http://stackoverflow.com/a/10406585/1048572). The `tostring` is wrong, if at all it needs to be `toString`, but nothing is really gained - it only would change what happens when you do `String(MainFunction)` – Bergi Aug 19 '14 at 11:31

0 Answers0