使用模块模式创建许多实例

时间:2019-03-05 02:44:58

标签: javascript encapsulation

我有两个文件:

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

1 个答案:

答案 0 :(得分:1)

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