简体   繁体   English

如何使用构造函数创建Javascript包?

[英]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. 在这里,我尝试创建一个名为com.matogen.ght的包,其中包含一个类Calendar。 I'd like the init() method to be called automatically when I instantiate the calendar object. 我想在实例化日历对象时自动调用init()方法。 The example below works, but I still have to explicitly call the init() method. 下面的示例有效,但我仍然必须显式调用init()方法。

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();

});

just change your init function like so 只需更改你的init函数

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();
    }
...

Well, as you are doing new com.matogen.ght.Calendar() , Calendar() is your constructor. 好吧,当你正在做new com.matogen.ght.Calendar()Calendar() 你的构造函数。

So: 所以:

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

... would be accurate. ......会准确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM