How to create a javascript package with constructor?

Here I tried to create a com.matogen.ght package with a class in it, Calendar. I would like the init () method to be called automatically when instantiating the calendar object. The example below works, but I still have to explicitly call the init () method.

var com = {
    matogen : {
        ght : {
            'Calendar' : function() {       

                this.init = function() {
                    console.log("This is my constructor");
                }

            }
        }
    } 
}

$(document).ready(function() {
    var cal = new com.matogen.ght.Calendar();
    cal.init();

});
+3
source share
2 answers

just change your function initas follows

this.init = (function() {
    console.log("This is my constructor");
}());

with a self-complete anonymous function or, if you want, just call the function as such

...
    Calendar : function() {       

        this.init = function() {
            console.log("This is my constructor");
        };
        this.init();
    }
...
+4

Well, how are you doing , - your constructor. new com.matogen.ght.Calendar()Calendar()

So:

var com = {
    matogen : {
        ght : {
            Calendar : function() {       
                console.log("This is my constructor");
            }
        }
    } 
}

... will be accurate.

+2

All Articles