Difference between using a module pattern and instantiating new objects
Asked Answered
H

1

8

I'm trying to restructure some javascript and I'm confused about the module pattern.

One way I have now is to simply declare a class containing all the functionality for a component like so

var Foo = function(){
    this.Bar = {};
    ...
}

and create a new instance for use in the component. But I've also read about the module pattern and I can't see what the benefit would be compared to what I have since it appears to do about the same, just in a more complicated way. Maybe I just haven't encountered the case that makes it a better choice. For example, a pattern like this:

var module = (function () {
    // private variables and functions
    var foo = 'bar';

    // constructor
    var module = function () {
    };

    // prototype
    module.prototype = {
        constructor: module,
        something: function () {
        }
    };

    // return module
    return module;
})();

var my_module = new module();

doesn't appear significantly different from what I already had. What does this pattern let me do that I can't do the other way?

Hankypanky answered 16/10, 2014 at 14:59 Comment(1)
This question has several good answers here: #5647758Macassar
M
3

The key difference between the two is in the first example, you can't have private variables and functions if you want to work with the prototype. You can have private variables and functions, but only if your public properties and methods are created in the constructor by attaching them to this.

Example 1 with a private variable and function:

var Foo = function(){
    var privateVar = "priv";

    function privateFunction(){
        console.log(privateVar);   
    }

    this.publicProperty = 1;

    this.publicFunction = function(){
        console.log(privateVar);
    }
}

The above is no problem if you don't want to use the prototype. However, if you do then there is no way to have private variables, without the new scope that your second example benefits from.

As you can see, you have to include everything within the constructor, whereas the second example you can leave the constructor just for initialising variables.

Conversely, the prototype methods in the second example are out of scope of the constructor, so they can't use any variables of functions within the constructor. All functions and variables that the prototype methods need must be declared in the outer closure scope.

Manteltree answered 16/10, 2014 at 15:36 Comment(1)
Thanks for the clarification, don't know why you got downvoted though :/Hankypanky

© 2022 - 2024 — McMap. All rights reserved.