Search code examples
javascriptencapsulation

Javascript class encapsulation behaviour


Can somebody explain me this javascript behaviour? I create 2 objects (x, y) and I call x.m() to modify private variable b on x. Then I call printing methods on both x and y and it produces following output. The output differs if the printing method p() is defined as a this property (1) or as a prototype (2).

this.p definition acts as expected: 2 objects have two private variables, modifying b property on x does not affect y's b property. But with A.prototype.p definition, b property seems to be static variable common for both objects x and y.

Described behaviour in code:

function A() {
  var b = "bbb";

  function f() {
    b = "ccc";
  }

  // 1)
  this.p = function() {
    console.log(b);
  };

  // 2)
  //A.prototype.p = function() {
  //  console.log(b);
  //};

  A.prototype.m = function() {
    f();
  };
}

var x = new A();
var y = new A();

x.m();
x.p();
y.p();

produces:

// 1)
bbbb
ccc

// 2)
//ccc
//ccc

Solution

  • In your example, you are overriding the prototype method p (as well as m) in the constructor of A, which means every time you create an instance the prototype method will change. All instances of A will then use the same method, which is the one of the last created instance.

    Have a look at this example which should show the behaviour you expect for your code:

    function A() {
      this.b = "bbb";
    }
    
    A.prototype.p = function() {
      console.log(this.b);
    };
    
    A.prototype.m = function() {
      this.b = "ccc";
    };
    
    
    var x = new A(),
      y = new A();
    
    x.m();
    x.p();
    y.p();