JavaScript - extract out function while keeping it

2019-03-06 00:05发布

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条回答
Animai°情兽
2楼-- · 2019-03-06 00:30

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);
查看更多
登录 后发表回答