首页 > 解决方案 > 使用模块模式创建许多实例

问题描述

我有两个文件:

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 中实现这一目标的正确方法是什么?

标签: javascriptencapsulation

解决方案


在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();

推荐阅读