How can I safely access other sibling functions and variables in a Javascript Module Pattern without accessing something in the containing scope?

别来无恙 提交于 2019-12-23 15:34:06

问题


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:


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");
}

// Assuming My.Namespaced is already defined:
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.



来源:https://stackoverflow.com/questions/3339668/how-can-i-safely-access-other-sibling-functions-and-variables-in-a-javascript-mo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!