多个现有构造函数的 JavaScript 通用方法

标签 javascript node.js constructor

我对 Javascript 处理构造函数、方法和原型(prototype)的方式相当陌生。

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

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 个构造函数(函数 Player),调用它两次来构建两个对象中的每一个,然后将通用方法分配给每个对象,然后使用原型(prototype)将不同的方法应用于每个对象,但是什么如果我已经编写了数百行代码并且我有许多从 PlayerBlack 和 PlayerWhite 构造函数创建的对象,我只想添加一个新方法,可以在通过 PlayerBlack 或 PlayerWhite 创建的所有现有对象之间使用?

我试过类似的东西,但它不起作用:

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

我正在寻找适用于 nodeJS 的解决方案。

最佳答案

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

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

创建共享父级:

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

关于多个现有构造函数的 JavaScript 通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34791380/

相关文章:

javascript - 什么是 javascript 反斜线以及它如何处理多行字符串?

node.js - 如何在 Mongoose 中填充嵌套实体?

javascript - 公会成员添加不起作用(discordjs)

javascript - 重写 JS 字符串构造函数 : Am I Way Off?

java - 如何防止 JPA 查询包含 String 构造函数,当 null String 值仅可用时抛出 NullPointerException

javascript - Jquery 模板性能

javascript - 重新选择不会正确内存同一组件的多个实例

javascript - 如何更改<select>的URL

javascript - 使用 Express JS 的 Angular 模板组件

c++ - 这是解决 mixins 构造函数问题的有效解决方法吗?