Skip to content Skip to sidebar Skip to footer

How To Do Prototypal Inheritance In Javascript?

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? fun

Solution 1:

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

functionPerson(name, age) {
    this.name = name;
    this.age = age;
}

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

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

Soldier.prototype = Object.create(Person.prototype); // is betterSoldier.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/

Post a Comment for "How To Do Prototypal Inheritance In Javascript?"