0

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?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

5 Comments

that's right. JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
So there is no way doing what I want using the Reveiling Module Pattern as I tried, I have to manipulate the prototype?
What If in your first example I want to avoid "this" to keep the variables encapsuled/private? I tried to adapt your example but didn't get it to work. wordA = 'xyz' instead of this.wordA = [...] and in doSomething() replace this.wordA by wordA. I get an error "wordA is not defined".
You can create a get method for wordA and wordB to keep them as private. function WordPair(wordA, wordB){ this.getWordA = function(){ return wordA; } this.getWordB = function(){ return wordB; } } WordPair.prototype.doSomething = function(){ const something = this.getWordA() + this.getWordB(); console.log(something); }
Why is it not possible to add the getter-functions to the prototype just as you did with "doSomething"? This prints 'undefined': function WordPair(_wordA){ let wordA = _wordA;} WordPair.prototype.getWordA = function(){ return this.wordA; } const wordPair = new WordPair('xyz'); console.log(wordPair.getWordA());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.