【问题标题】:How to do prototypal inheritance in JavaScript?如何在 JavaScript 中进行原型继承?
【发布时间】:2012-10-31 07:57:15
【问题描述】:

我已经尝试了几种方法,但我无法做到。

在下一个示例中,我希望 Soldier 获取 Person 的所有属性,并允许添加更多属性。如何正确操作?

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

【问题讨论】:

标签: javascript inheritance prototype


【解决方案1】:

您没有Soldier 构造函数。你需要先做到这一点。然后将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!");
};

然后像这样使用它:

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

s.good_hi("Hello");

演示: http://jsfiddle.net/3kGGA/

【讨论】:

  • 您忘记了Soldier.prototype.constructor = Soldier; 否则,构造函数将是您分配的原型对象中的Person
  • @millimoose:添加完成。
猜你喜欢
  • 2011-03-02
  • 2010-09-28
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多