简体   繁体   English

如何在 JavaScript 中进行原型继承?

[英]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.在下一个示例中,我希望士兵获得 Person 的所有属性,并允许添加更多属性。 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.你没有一个Soldier构造函数。 You need to make that first.你需要先做到这一点。 Then you'd apply the Person constructor to new Soldier instances.然后将Person构造函数应用于新的Soldier实例。

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/演示: http : //jsfiddle.net/3kGGA/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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