的initialize
功能是真正私有的,以你在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
实例。你有谷歌的负载回调调用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
实例,那么很好,绝对要去构造函数route。但是,如果不使用,那么如果使用已有的对象(对函数的调用的执行上下文),则会涉及更少的麻烦。
题外话:强烈建议声明你CAREERS
变量。现在,您的代码就像是The Horror Of Implicit Globals。
感谢您对self.init()的帮助和提示。快速的问题,为什么这必须分配给一个变量? –
@Giles:因为JavaScript中的this与您可能使用的其他语言(如Java,C++,C#)中的this不同,所以在JavaScript中,this完全由*如何定义称为*,而不是*其中函数被定义*。当jQuery调用你的'onload'处理函数时,它会将'this'设置为'window'对象,而不是你的'Career'实例。所以我们利用这个事实,即你已经将该处理程序定义为构造函数调用的上下文的闭包,并使用变量来记住对正在构建的对象的引用。 (请参阅我添加的有关'this'的链接。) –
嗯好吧,这是有道理的,我忘了jQuery的这个。感谢其他的信息,解剖和理解需要一段时间,但这非常有帮助。 –