views:

20

answers:

1

I have a Javascript Object structured after the Module Pattern. I have several private function in it which are called from other sibling "private" functions. How can I access another variable/function without the potential to accidentally access a global/external variable/object/function?

function doSomething() {
  alert("Something I don't want to do");
}

var My.Namespaced.SingletonClass = (function() {
  var init = function() {
    doSomething();
  }

  var doSomething = function() {
    alert("Something I want to do");
  }

  return {
    "init": init;
  }
})();

My.Namespaced.SingletonClass.init();

My guess is that the above code would in fact access the correct, inner doSomething function, but I'd like some more security than that. How can I explicitly address the inner/nested function without fear of accidentally calling functions or addressing objects in the scope around my singleton?

+1  A: 

Short version: you can't. If doSomething isn't defined as a sibling of init, then JavaScript will search successively broader scopes until it finds a doSomething function, or it runs out of scopes to search.

Longer version: you can prevent this sort of behavior by using a private object to hold your private helper functions, like this:

function doSomething() {
  alert("Something I don't want to do");
}

var My.Namespaced.SingletonClass = (function() {
  var helpers = {};

  helpers.doSomething = function() {
    alert("Something I want to do");
  }

  var init = function() {
    helpers.doSomething();
  }

  return {
    init: init
  }
})();

My.Namespaced.SingletonClass.init();

I'm not sure if it's important that the helper functions are truly siblings (but I don't see why that would particularly matter).

Also keep in mind that My and My.Namespaced need to be defined before you tack on SingletonClass - and there's no need to use JSON-style quoting for keys in the object you're returning.

Matt Ball
I like the 'helpers' private object convention you suggest... thanks!
RenderIn
No problemo! Glad to help.
Matt Ball