initialize 函数对您在 this.init 上的函数是真正私有的。它不能从 this.init 函数的外部访问,除非您采取措施使其可访问。
但我认为您不需要额外的间接层:
google.setOnLoadCallback(function(){$(document).ready(CareersInit);});
function CareersInit()
{
CAREERS = new Careers();
CAREERS.init();
}
function Careers()
{
var self = this;
this.init = function()
{
//Usual google maps stuff here
};
$('body').bind('onload', function() {
self.init();
});
}
不过,另外,您的代码正在尝试两次初始化 Careers 实例。您有 Google 的加载回调调用 jQuery 的 ready 函数,然后调用您的 CareersInit 函数,该函数调用 CAREERS.init。但是您也有Careers 结构安排单独的页面加载回调。 (这可能会或可能不会运行,这取决于 Google 何时触发 setOnLoadCallback 回调。)
我会摆脱那些对init 的电话之一。
在对另一个答案的评论中,您说过您想知道“最佳”方法是什么。我必须更多地了解你在做什么,但我可能会这样做:
(function() {
// Our single Careers instance
var CAREERS;
// Ask Google to call us when ready
google.setOnLoadCallback(function(){
// Just in case Google is ready before the DOM is,
// call our init via `ready` (this may just call
// us immediately).
$(document).ready(CareersInit);
});
// Initialize our single instance
function CareersInit()
{
CAREERS = new Careers();
CAREERS.init();
}
// Constructor
function Careers()
{
}
// Career's init function
Careers.prototype.init = Careers_init;
function Careers_init()
{
//Usual google maps stuff here
}
})();
...除了如果您只拥有 一个 实例(并且您确定这不会改变),则根本不需要构造函数:
(function() {
// Our data; the function *is* the single object
var someData;
// Ask Google to call us when ready
google.setOnLoadCallback(function(){
// Just in case Google is ready before the DOM is,
// call our init via `ready` (this may just call
// us immediately).
$(document).ready(CareersInit);
});
// Initialize our single instance
function CareersInit()
{
someData = "some value";
}
})();
那里,函数范围是单个实例;不需要单独的构造函数,playing games with this 等。请注意,我们没有创建任何全局变量,someData 的作用域是匿名函数。解释器对该函数的调用是我们的单个对象。
如果您需要多个Career 实例,那太好了,一定要走构造函数路线。但如果没有,如果你使用你已经拥有的对象(函数调用的执行上下文),就会少很多麻烦。
题外话:强烈建议声明您的CAREERS 变量。使用您现在的代码,您将成为The Horror Of Implicit Globals 的牺牲品。