2

I've tried several ways but I couldn't do it.

On the next example I want the Soldier gets all properties of Person, and allowing to add more properties. How to do it correctly?

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.hi = function (message) {
    console.log(message + "!!!");
};

var Soldier = new(Person); // it is not the way to do it

Soldier.prototype.good_hi = function (message) {
    console.log("Sir! " + message + ", sir!");
};
2
  • 1
    Does googling for "javascript inheritance" come up with nothing? Commented Nov 11, 2012 at 19:16
  • phrogz.net/JS/classes/OOPinJS2.html Commented Nov 11, 2012 at 19:18

1 Answer 1

2

You don't have a Soldier constructor. You need to make that first. Then you'd apply the Person constructor to new Soldier instances.

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.hi = function (message) {
    console.log(message + "!!!");
};

function Soldier(name, age) {
    Person.apply(this, arguments);
}

Soldier.prototype = Object.create(Person.prototype); // is better
Soldier.prototype.constructor = Soldier;

Soldier.prototype.good_hi = function (message) {
    console.log("Sir! " + message + ", sir!");
};

Then use it like this:

var s = new Soldier("Bob", 23);

s.good_hi("Hello");

DEMO: http://jsfiddle.net/3kGGA/

Sign up to request clarification or add additional context in comments.

2 Comments

You forgot Soldier.prototype.constructor = Soldier; Otherwise, the constructor will be Person from the prototype object you assign.
@millimoose: added it in to be complete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.