I’m having trouble accessing a function inside an object.
My setup is as such..
google.setOnLoadCallback(function(){$(document).ready(CareersInit);});
function CareersInit()
{
CAREERS = new Careers();
CAREERS.init();
}
function Careers()
{
this.init = function()
{
function initialize()
{
//Usual google maps stuff here
}
}
$('body').bind('onload', function() {
initialize();
});
}
With this setup, initialize doesn’t run but if I take my google maps variables/functions out of the initialize function then it work’s but my understanding (from google docs) is that initialize should always be a function that contains the google maps variables/functions etc.
Even if that is the right way to go it would be great to find out how to access functions when they are inside an objects method just for debug purposes in the console. I thought
CAREERS.init.initialize();
would work but it doesn’t.
Any help or advice would be greatly appreciated.
Thanks
Giles
The
initializefunction is truly private to the function you’re putting onthis.init. It cannot be accessed from outside thatthis.initfunction unless you do something to make it accessible.But I don’t think you need that extra layer of indirection:
Separately, though, your code is trying to initialize the
Careersinstance twice. You have Google’s load callback calling jQuery’sreadyfunction which then calls yourCareersInitfunction which callsCAREERS.init. But you also have theCareersconstructure scheduling a separate page load callback. (That one may or may not run, it depends on when Google fires thesetOnLoadCallbackcallback.)I’d get rid of one of those calls to
init.In a comment on another answer, you’ve said you want to know what the “best” way to do it is. I’d have to know more about what you’re doing, but I’d probably do it like this:
…except that if you’re going to just have one instance (and you’re sure that’s not going to change), there’s really no call for a constructor function at all:
There, the function scope is the single instance; no need for separate constructor functions, playing games with
this, etc. Note that we’re not creating any globals,someDatais scoped to the anonymous function. The call that the interpreter makes to that function is our single object.If you’re ever going to need more than one
Careerinstance, then great, definitely go the constructor function route. But if not, there’s a lot less fuss involved if you use the object you already have (the execution context of the call to the function).Off-topic: Strongly recommend declaring your
CAREERSvariable. With your code as it is now, you’re falling prey to The Horror Of Implicit Globals.