如何在JavaScript中进行原型继承? [英] How to do prototypal inheritance in JavaScript?

查看:52
本文介绍了如何在JavaScript中进行原型继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了几种方法,但我做不到.

I've tried several ways but I couldn't do it.

在下一个示例中,我希望士兵获得Person的所有属性,并允许添加更多属性.如何正确执行?

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

推荐答案

您没有Soldier构造函数.您需要先做到这一点.然后,将Person构造函数应用于新的Soldier实例.

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

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

这篇关于如何在JavaScript中进行原型继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆