Search code examples
javascriptencapsulation

How to access private variable using a public method within same object in javascript?


I am trying to understand Encapsulation through this link

function Test() {
  var prop1 = "one";
  this.prop2 = "two";

  function meth1() {
    console.log("Inside meth1" + prop1);
  }

  this.meth2 = function() {
    console.log(this.prop2 + "................, " + meth1());
  };

  this.meth4 = function(val) {

    prop1 = val;

    console.log("inside meth4" + prop1);
  }
}

var tc = new Test();
var result1 = tc.meth2();
var result3 = tc.prop1;

According to the link meth1() accessed through this.meth2 should work, but to my surprise i got undefined.

Could you please shed some light on what is happening here. I am using IE 9 for this and getting

LOG: Inside meth1one 
LOG: two................, undefined 

Solution

  • in addition to @Michael's answer, when you try to make a function as a class, remember to return value. This value will be publicly available. In a class structure, var result3 = tc.prop1; should return undefined. Only way to access it should be a function. Following is a representation

    function Test() {
      
      // To hold context as object inside functions
      var self = this;
      self.prop1 = "one";
      self.prop2 = "two";
    
      // method to access prop1
      function meth1() {
        return self.prop1;
      }
    
      // method to access prop2
      function meth2() {
        return self.prop2;
      };
      
      // Properties that will be publically available.
      // Never add private variables here.
      return{
        "meth1":meth1,
        "meth2":meth2
      }
    }
    
    var tc = new Test();
    var result1 = tc.meth1(); // Should be "one"
    var result2 = tc.prop1;   // Should be "undefined". Private property
    var result3 = tc.meth2(); // Should be "two"
    
    console.log(result1,result2,result3)