在这里,我尝试创建一个名为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();
});
答案 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");
}
}
}
}
......准确无误。