JavaScript常见的方法来多个现有的构造函数

我对Javascript处理构造函数,方法和原型的方式颇为陌生。

我想创build两个具有许多不同的自定义方法的构造函数,但也有一些共同的方法。 目前我做这样的事情:

function PlayerWhite(n,s) { this.name = n; this.state = s;} function PlayerBlack(n,c) { this.name = n; this.county = c; } PlayerWhite.prototype.showCounty = function() { alert(this.county);} PlayerBlack.prototype.showState = function() { alert(this.state);} PlayerWhite.prototype.showName = function() { alert(this.name); } PlayerBlack.prototype.showName = function() { alert(this.name); } 

所以这两个构造函数的“showName”方法的内容是相同的。 “showName”的代码可能会改变,这两个都是一样的,所以我不想在每次执行showName方法的更新时进行双重编辑。

当然,我只能使用1个构造函数(function Player),调用它两次来构build这两个对象,然后将通用方法分配给每个对象,然后使用原型将不同的方法应用于每个对象,但是如果我已经写了数百行的代码,我有很多从PlayerBlack和PlayerWhite构造函数创build的对象,我只是想添加一个新的方法,可以通过PlayerBlack或PlayerWhite创build的所有现有的对象之间使用?

我尝试了这样的东西,但它不工作:

 PlayerWhite.prototype.showName, PlayerBlack.prototype.showName = function() { alert(this.name); } 

我正在寻找一个解决scheme,将在nodeJS工作。

分享一个方法,像这样分配:

 PlayerWhite.prototype.showName = function() { alert(this.name); } PlayerBlack.prototype.showName = PlayerWhite.prototype.showName; 

要创build共享的父级:

 Shared = function() { } //here define shared methods Shared.prototype.showName = function() { alert(this.name); } PlayerWhite.prototype = new Shared(); PlayerBlack.prototype = new Shared(); //here define non-shared methods PlayerWhite.prototype.showCounty = function() { alert(this.county);} PlayerBlack.prototype.showState = function() { alert(this.state);} 

你正在寻找简单的inheritance方法。 请看MDN的进一步解释 – 这里真的很好解释。

https://developer.mozilla.org/pl/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

另外 – 如果你期待使用nodeJs,请看看它的“模块”。

https://nodejs.org/api/modules.html

你可以把两个方法结合起来,像这样:

 var BaseModel = require('PATHTOBASEMODEL/base_model'); ExtendedModel = Object.create(BaseModel); ExtendedModel.prototype.yourFunction = function () { /* ... */ }; module.exports = ExtendedModel;