簡體   English   中英

如何在 JavaScript 中進行原型繼承?

[英]How to do prototypal inheritance in JavaScript?

我嘗試了幾種方法,但我做不到。

在下一個示例中,我希望士兵獲得 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!");
};

你沒有一個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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM