JavaScript - extract out function while keeping it private

前端 未结 1 1991
深忆病人
深忆病人 2021-01-28 10:54

Currently I have this structure:

(function(myScope) {
  myScope.public = function() {alert(\"I\'m public!\")};
  myScope.privileged = function() {alert(\"I can c         


        
相关标签:
1条回答
  • 2021-01-28 11:25

    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);
    
    0 讨论(0)
提交回复
热议问题