0

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.

Boyang
  • 2,520
  • 5
  • 31
  • 49

1 Answers1

0

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for your answer. I'm not sure whether I get it. If the implementation of makeAlerter() is in another file, doesn't it mean that anyone can open the console and invoke it? For example, if the private function I have actually involves ajax call: `function myPrivateFuncImpl() {$.ajax(...);}` then how can I prevent curious users from invoke it? – Boyang Apr 30 '14 at 01:18
  • Yes, you can put all of the three parts in different files. Notice that you *never* can prevent "curious users" from inspecting and calling your code. The concept of privacy in javascript "only" goes as far as nobody can mess with your local `private` variable, which can contain parts of your private state. In the above case, everybody has access to the `makeAlerter` function, but they don't know the `state` you've actually used. Similarly, everybody could have access to your ajax function, but they wouldn't know the parameters to pass. – Bergi Apr 30 '14 at 14:15