JavaScript - extract out function while keeping it private

时光毁灭记忆、已成空白 提交于 2019-12-04 07:09:40

问题


Currently I have this structure:

(function(myScope) {
  myScope.public = function() {alert("I'm public!")};
  myScope.privileged = function() {alert("I can call private!"); private();};
  var private = function() {alert("I'm private!")};
})(window.myObj);

It works fine. private is not accessible from the outside world while privileged can call it. But now the private parts are too big such that I hope to extract it out. I want to keep it inaccessible from the outside but it needs to be invoked by the privileged functions. Is there a way to achieve that?

UPDATE:

The above is just an example. The general problem is that as the app extends, the single js file grows to become long and unmanageable. The goal is to split such js file into module, without compromising privacy.


回答1:


You will need to break your code down into smaller parts. For each thing, you might want to make the instance reference local-scoped, but you can import the class/code/functionality from a different file.

Blowing up your example to three files:

function makeAlerter(state) {
  return function() {
    alert("I'm "+state);
  };
}

(function(myScope) {
  var private = makeAlerter("private"); // not the whole private coding here
  myScope.privileged = function() { // but the privileged code needs to stay
    alert("I can call private!"); private();
  };
})(window.myObj);

(function(myScope) {
  myScope.public = function() {alert("I'm public!")};
})(window.myObj);


来源:https://stackoverflow.com/questions/23364382/javascript-extract-out-function-while-keeping-it-private

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