1

Lets say I have a JavaScript class that takes a whole lot of settings in the constructor, and then only have one method that the user of the class might want to call multiple times. Here's an example:

class Doer {

    constructor(settings) {
        this._settings = settings;
    }

    function doIt(params) {
        //Return something based on this._settings and params.
    }

}

let myDoer = new Doer(mySettings);
myDoer.doIt(params);

An alternative approach would be to use a closure:

function createDoer(settings) {
    return function doIt(params) {
        // Return something based on settings and params.
    }
}

let myDoer = createDoer(mySettings);
myDoer(myParams);

What are the pros and cons of these two different ways of doing it? When should I use a class, and when should I use a closure?

On one hand, using a class seems like overly relying on OOP when a simple functional concept is enough. But on the other hand, the class is more extensible in case the needs of the project would change.

  • 4
    They are not interchangeable. E.g. you can't pass your class to map or fold – Caleth Feb 10 '17 at 10:26
  • First: Classes are only syntactic sugar for closures. developer.mozilla.org/en/docs/Web/JavaScript/Reference/classes That said, it is up to you and to your taste in this case, what feels better. – Thomas Junk Feb 10 '17 at 10:39
  • Why do people never think they can switch to a class later "in case the needs of the project would change?" – Karl Bielefeldt Feb 10 '17 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.