Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these three module pattern implementations in JavaScript?

I've seen the following three code blocks as examples of the JavaScript module pattern. What are the differences, and why would I choose one pattern over the other?

Pattern 1

function Person(firstName, lastName) {
    var firstName = firstName;
    var lastName = lastName;

    this.fullName = function () {
        return firstName + ' ' + lastName;
    };

    this.changeFirstName = function (name) {
        firstName = name;
    };
};

var jordan = new Person('Jordan', 'Parmer');

Pattern 2

function person (firstName, lastName) { 
    return {
        fullName: function () {
            return firstName + ' ' + lastName;
        },

        changeFirstName: function (name) {
            firstName = name;
        }
    };
};

var jordan = person('Jordan', 'Parmer');

Pattern 3

var person_factory = (function () {
    var firstName = '';
    var lastName = '';

    var module = function() {
        return {
            set_firstName: function (name) {
                               firstName = name;
                           },
            set_lastName: function (name) {
                              lastName = name;
                          },
            fullName: function () {
                          return firstName + ' ' + lastName;
                      }

        };
    };

    return module;
})();

var jordan = person_factory();

From what I can tell, the JavaScript community generally seems to side with pattern 3 being the best. How is it any different from the first two? It seems to me all three patterns can be used to encapsulate variables and functions.

NOTE: This post doesn't actually answer the question, and I don't consider it a duplicate.

like image 252
Jordan Parmer Avatar asked Dec 10 '12 18:12

Jordan Parmer


People also ask

What are the three main benefits of JavaScript patterns?

Design patterns are reusable solutions to commonly occurring problems in software design. They are proven solutions, easily reusable and expressive. They lower the size of your codebase, prevent future refactoring, and make your code easier to understand by other developers.

What is the module pattern in JavaScript?

Module pattern. The Module pattern is used to mimic the concept of classes (since JavaScript doesn't natively support classes) so that we can store both public and private methods and variables inside a single object — similar to how classes are used in other programming languages like Java or Python.

What are different design patterns in JavaScript?

They are categorized in three groups: Creational, Structural, and Behavioral (see below for a complete list). In this tutorial we provide JavaScript examples for each of the GoF patterns. Mostly, they follow the structure and intent of the original pattern designs.

How many types of design patterns are there in JavaScript?

The book explores the capabilities and pitfalls of object-oriented programming, and describes 23 useful patterns that you can implement to solve common programming problems. These patterns are not algorithms or specific implementations.


2 Answers

I don't consider them module patterns but more object instantiation patterns. Personally I wouldn't recommend any of your examples. Mainly because I think reassigning function arguments for anything else but method overloading is not good. Lets circle back and look at the two ways you can create Objects in JavaScript:

Protoypes and the new operator

This is the most common way to create Objects in JavaScript. It closely relates to Pattern 1 but attaches the function to the object prototype instead of creating a new one every time:

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

Person.prototype.fullName = function () {
    return this.firstName + ' ' + this.lastName;
};

Person.prototype.changeFirstName = function (name) {
    this.firstName = name;
};

var jordan = new Person('Jordan', 'Parmer');

jordan.changeFirstName('John');

Object.create and factory function

ECMAScript 5 introduced Object.create which allows a different way of instantiating Objects. Instead of using the new operator you use Object.create(obj) to set the Prototype.

var Person =  {
    fullName : function () {
        return this.firstName + ' ' + this.lastName;
    },

    changeFirstName : function (name) {
        this.firstName = name;
    }
}

var jordan = Object.create(Person);
jordan.firstName = 'Jordan';
jordan.lastName = 'Parmer';

jordan.changeFirstName('John');

As you can see, you will have to assign your properties manually. This is why it makes sense to create a factory function that does the initial property assignment for you:

function createPerson(firstName, lastName) {
    var instance = Object.create(Person);
    instance.firstName = firstName;
    instance.lastName = lastName;
    return instance;
}

var jordan = createPerson('Jordan', 'Parmer');

As always with things like this I have to refer to Understanding JavaScript OOP which is one of the best articles on JavaScript object oriented programming.

I also want to point out my own little library called UberProto that I created after researching inheritance mechanisms in JavaScript. It provides the Object.create semantics as a more convenient wrapper:

var Person = Proto.extend({
    init : function(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    },

    fullName : function () {
        return this.firstName + ' ' + this.lastName;
    },

    changeFirstName : function (name) {
        this.firstName = name;
    }
});

var jordan = Person.create('Jordan', 'Parmer');

In the end it is not really about what "the community" seems to favour but more about understanding what the language provides to achieve a certain task (in your case creating new obejcts). From there you can decide a lot better which way you prefer.

Module patterns

It seems as if there is some confusion with module patterns and object creation. Even if it looks similar, it has different responsibilities. Since JavaScript only has function scope modules are used to encapsulate functionality (and not accidentally create global variables or name clashes etc.). The most common way is to wrap your functionality in a self-executing function:

(function(window, undefined) {
})(this);

Since it is just a function you might as well return something (your API) in the end

var Person = (function(window, undefined) {
    var MyPerson = function(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    };

    MyPerson.prototype.fullName = function () {
        return this.firstName + ' ' + this.lastName;
    };

    MyPerson.prototype.changeFirstName = function (name) {
        this.firstName = name;
    };

    return MyPerson;
})(this);

That's pretty much modules in JS are. They introduce a wrapping function (which is equivalent to a new scope in JavaScript) and (optionally) return an object which is the modules API.

like image 177
Daff Avatar answered Sep 28 '22 05:09

Daff


First, as @Daff already mentioned, these are not all module patterns. Let's look at the differences:

Pattern 1 vs Pattern 2

You might omit the useless lines

var firstName = firstName;
var lastName = lastName;

from pattern 1. Function arguments are already local-scoped variables, as you can see in your pattern-2-code.

Obviously, the functions are very similar. Both create a closure over those two local variables, to which only the (exposed) fullName and the changeFirstName functions have access to. The difference is what happens on instantiation.

  • In pattern 2, you just return an object (literal), which inherits from Object.prototype.
  • In pattern 1, you use the new keyword with a function that is called a "constructor" (and also properly capitalized). This will create an object that inherits from Person.prototype, where you could place other methods or default properties which all instances will share.

There are other variations of constructor patterns. They might favor [public] properties on the objects, and put all methods on the prototype - you can mix such. See this answer for how emulating class-based inheritance works.

When to use what? The prototype pattern is usually preferred, especially if you might want to extend the functionality of all Person instances - maybe not even from the same module. Of course there are use cases of pattern 1, too, especially for singletons that don't need inheritance.

Pattern 3

…is now actually the module pattern, using a closure for creating static, private variables. What you export from the closure is actually irrelevant, it could be any fabric/constructor/object literal - still being a "module pattern".

Of course the closure in your pattern 2 could be considered to use a "module pattern", but it's purpose is creating an instance so I'd not use this term. Better examples would be the Revealing Prototype Pattern or anything that extends already existing object, using the Module Pattern's closure - focusing on code modularization.

In your case the module exports a constructor function that returns an object to access the static variables. Playing with it, you could do

var jordan = person_factory();
jordan.set_firstname("Jordan");
var pete = person_factory();
pete.set_firstname("Pete");
var guyFawkes = person_factory();
guyFawkes.set_lastname("Fawkes");

console.log(jordan.fullname()); // "Pete Fawkes"

Not sure if this was expected. If so, the extra constructor to get the accessor functions seems a bit useless to me.

like image 37
Bergi Avatar answered Sep 28 '22 07:09

Bergi