0

For the following function I was expecting a and b to have their own versions of array, hence expecting the output to be false, but it prints true. Can anyone please explain, why ?

 function Test() { 
    var a = [1,2,3]; 
    Test.prototype.getArray = function() { return a; };
 }

var a = new Test();
var b = new Test();

console.log(a.getArray() === b.getArray());
anivas
  • 6,437
  • 6
  • 37
  • 45

1 Answers1

2

Every Test object inherits the same prototype. The exact same prototype. Since you're overwriting a prototype function, it's overwriting it for all objects of that type.

Example:

function log(msg) {
  document.querySelector('pre').innerText += msg + '\n';
}

function Person(name) {
  this.name = name;
}
Person.prototype.sayHello = function() {
  log('Hello, ' + this.name);
};

var bob = new Person('Bob');
var alice = new Person('Alice');
bob.sayHello();
alice.sayHello();

// Overwriting the prototype function
Person.prototype.sayHello = function() {
  log('Goodbye, ' + this.name);
};
bob.sayHello();
alice.sayHello();
<pre></pre>

If you absolutely need to access private data in a function using a standard constructor, you'll need to define the function within the constructor itself.

function Test() {
  var a = [1,2,3];
  this.getArray = function() {
    return a;
  };
}

Be aware that this negates a lot of the space and performance optimizations you gain from prototype inheritance in many implementations.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91