简体   繁体   中英

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?

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!");
};

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/

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