javascript - 使用模块模式创建许多实例
问题描述
我有两个文件:
let WordPair = function(wordA, wordB) {
function doSomething() { ... };
const smth = wordA + wordB;
return {doSomething, smth};
};
module.exports = WordPair;
-
let wordpair = require('./WordPair.js')('dog', 'cat');
wordpair.doSomething();
现在效果很好,但我想做的是创建许多 WordPair 实例,例如:
let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(new WordPair('xyz', 'abc'));
}
换句话说:如何在 Java 中使用类的实例。在 Javascript 中实现这一目标的正确方法是什么?
解决方案
在javascript中,您可以使用原型模式来实现
假设 doSomething 是结合 wordA 和 wordB 的类方法
function WordPair(wordA, wordB){
this.wordA = wordA;
this.wordB = wordB;
}
WordPair.prototype.doSomething = function(){
const something = this.wordA + this.wordB;
console.log(something);
}
const wordPair = new WordPair('xyz', 'abc');
wordPair.doSomething();
或者更多的es6类方式
class WordPair {
constructor(wordA, wordB){
this.wordA = wordA;
this.wordB = wordB;
}
doSomething(){
const something = this.wordA + this.wordB;
console.log(something);
}
}
const wordPair = new WordPair('xyz', 'abc');
wordPair.doSomething();
推荐阅读
- python - 如何在 Pycharm 中使用 Pandas
- node.js - AWS Lambda 在正文响应中返回 base64 编码数据和文本字符串
- mesos - 未通过 Marathon 健康检查的应用程序警报
- ruby-on-rails - 条纹元素表单在 Rails 应用程序中不可见
- angularjs - 如何过滤的值
- python - 通过对象列表中的每个元素索引查找除零以外的最小值
- c - 尝试在 C 程序中声明 5D 数组时出现分段错误
- yolo - YOLO:如何在暗网代码中改变mAP计算的频率
- javascript - ReactJSL如何使用按钮定位地图函数中的单个元素
- excel - 在未激活/未选择的工作表中添加图表(VBA Excel)