Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Javascript package with a constructor in it?

Here I attempted to create a package called com.matogen.ght with a class in it, Calendar. I'd like the init() method to be called automatically when I instantiate 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();

});
like image 782
sparkyspider Avatar asked Aug 12 '26 18:08

sparkyspider


1 Answers

just change your init function like so

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

with a self executed anonymous function or, if you prefer, just call the function itself like so

...
    Calendar : function() {       

        this.init = function() {
            console.log("This is my constructor");
        };
        this.init();
    }
...
like image 180
Fabrizio Calderan Avatar answered Aug 15 '26 08:08

Fabrizio Calderan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!