mondrakerrider
mondrakerrider

Reputation: 25

Module pattern vs constructor in Javascript

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!

Upvotes: 2

Views: 87

Answers (1)

t.niese
t.niese

Reputation: 40882

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

Upvotes: 1

Related Questions