junlin
junlin

Reputation: 2045

ES5 puzzle of private variable defined in constructor

I am reading the Private Variable section in "Professional JavaScript for Web Developers 3rd Edition", and feel puzzled about one of the sample codes:

function Person(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

var person1 = new Person('p1');
person1.setName('p11');
person1.getName();  // 'p11'

var person2 = new Person('p2');
person2.getName();  // 'p2'

The getName() method accesses the name variable via the closure and scope chain, while the setName() method assigns a new value to name.

Question:

Where does the name variable exist?

Why does every instance of Person have a different name, so that if one instance modifies the name variable it would not affect other instances?

====================================

I think that every time an instance is created with new, there a Person Activation Object is being created. The name variable in the every Person Activation Object is different.

Upvotes: 0

Views: 184

Answers (1)

trincot
trincot

Reputation: 350365

This behaviour has nothing to do with new.

Every time you invoke Person, a new, separate instance of the parameter variable name is created. The code inside that function can access that variable. There is nothing more to it.

This is true for parameter variables in every function you may declare. As long as it is possible to reference such variables they remain in memory -- they are not garbage collected.

Calling Person twice, is in essence not much different then calling 2 different functions which both have the same parameters and methods:

function Person1(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

function Person2(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

var person1 = new Person1('p1');
person1.setName('p11');
person1.getName();  // 'p11'

var person2 = new Person2('p2');
person2.getName();  // 'p2'

Of course, here person1 and person2 are no longer the instance of the same constructor, but besides that the principle of separate variable instances and scopes is the same.

Upvotes: 1

Related Questions