Ali
Ali

Reputation: 267317

Inheriting parent's properties in a Javascript child object

If I have these 2 functions:

function Person(age)
{
   this.setAge = function(newAge)
   {
       age = newAge;
   }

   this.getAge = function()
   {
      alert(age);
   }
}

function Bob(age)
{
    Person.call(this, age);
    this.foo = function() {} //etc
}

Bob.prototype = new Person();

bob = new Bob(43);
bob.getAge();

Will the correct age (43) be alerted?

Upvotes: 0

Views: 242

Answers (1)

chuckj
chuckj

Reputation: 29655

The answer is yes but calling setAge will not change the foo functions version of age since they are different captured variables. Consider moving to a style that looks more like,

function Person(age) { this.age = age; }
Person.prototype.getAge = function() { return this.age; };
Person.prototype.setAge = function(value) { this.age = value; }
function Bob(age) { Person.call(this, age); }
Bob.prototype = new Person();
Bob.prototype.foo = function() { /* ... */ }

Note that foo() and getAge() now see the same value for this.age. Also this is much more space efficient since the instance of Person and Bob only consume one slot per instance instead of 3 to 4 and do not require closure environments to be created for getAge, setAge and foo.

Upvotes: 1

Related Questions