Search code examples
javascriptprivate

Prive Function in JS access to variables


I have a JS function with the structure of

 function myFunc (method){
      this.type = method;
      this.border = '20';
      this.add = function(){
           // some codes
           privateFunc();
      }

      var privateFunc = function(){
           //my private function
      }
  }

The problem is, that the private function does not have access to any of the variables (this.type, this.border). They are not defined inside it! Why not?! How can I have a private function there with access to the variables?


Solution

  • Just for the sake of completeness

     function myFunc (method){ 
          this.type = method; 
          this.border = '20'; 
          // take a reference to the current object
          var self = this;
          this.add = function(){ 
               // some codes 
               privateFunc(); 
          } 
    
          var privateFunc = function(){ 
    
               //now you can access your members via self variable
               self.border = 10;
          } 
      } 
    

    The clue here is the usage of closure.