Reputation: 47
I have two files:
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();
Now that works fine, but what I want to do is creating many instances of WordPair, for example like this:
let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(new WordPair('xyz', 'abc'));
}
In other words: How you would use instances of a class in Java. What's the correct way to achieve this in Javascript?
Upvotes: 0
Views: 44
Reputation: 761
in javascript, you can use prototype pattern to achieve that
suppose doSomething is class method that combine the wordA and 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();
or more es6 class way
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();
Upvotes: 1