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

时间:2012-04-24 07:24:31

标签: javascript constructor package

在这里,我尝试创建一个名为com.matogen.ght的包,其中包含一个类Calendar。我想在实例化日历对象时自动调用init()方法。下面的示例有效,但我仍然必须显式调用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();

});

2 个答案:

答案 0 :(得分:4)

只需像这样更改init功能

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

使用自执行匿名函数,或者,如果您愿意,只需像这样调用函数本身

...
    Calendar : function() {       

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

答案 1 :(得分:2)

好吧,当您正在执行 new com.matogen.ght.Calendar()时,Calendar() 是您的构造函数。

所以:

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

......准确无误。