3

在这里,我尝试创建一个名为 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();

});
4

2 回答 2

4

像这样改变你的init功能

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

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

...
    Calendar : function() {       

        this.init = function() {
            console.log("This is my constructor");
        };
        this.init();
    }
...
于 2012-04-24T07:28:07.213 回答
2

好吧,正如您所做的那样,您的构造函数。 newcom.matogen.ght.Calendar()Calendar()

所以:

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

......将是准确的。

于 2012-04-24T08:58:30.137 回答