2

What are the pros/cons of using module pattern versus a simple object constructor like this?:

function Car() {
  var _mileage = 123;
  this.bar = function() {
      console.log(_mileage);
  }
}

Both allow for private variables and methods, then why and when is module pattern needed or recommended?

Thanks in advance!

9
  • 6
    It's 2020 on the calendar - you can use class already. Commented Jul 6, 2020 at 8:30
  • That's not the module pattern. It's just a plain old ES5 constructor function. Commented Jul 6, 2020 at 8:31
  • arent private properties defined with # infront of it? like #mileage = 123; Commented Jul 6, 2020 at 8:32
  • @Ifaruki that's a proposed feature. Commented Jul 6, 2020 at 8:34
  • @t.niese ah okey Commented Jul 6, 2020 at 8:36

1 Answer 1

1

Both create the module pattern and the one you show uses scopes to limit the access to variables and functions, and create a closure over those.

The module pattern ist primarily used to create one object:

var car = (function () {
    var _mileage = 123;

    function bar() {
      console.log(_mileage);
    }

    return {
        bar: bar
    };
}());

While the one you show allows creating multiple objects that are an instance of Car.

var car1 = new Car();
var car2 = new Car();

console.log(car1 instanceof Car); // true
console.log(car2 instanceof Car); // true

Sign up to request clarification or add additional context in comments.

5 Comments

Ok so before ES6 how would you emulate a class (having multiples instances of Car)?
@mondrakerrider I don't understand what you mean. The code you showed in your question allows creating multiple instances of Car.
I mean, before ES6 classes, what was a valid approach to emulate classes with all the advantages they provide? a simple constructor like the one I showed is ok?
@mondrakerrider That's a new/different topic then you asked in your question, and there are many Q&A about that here on SO. MDN: Classes 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
@t.niese "primarily"

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.