简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM