Difference between using a module pattern and instantiating new objects

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?


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.

链接地址: http://www.djcxy.com/p/23202.html

上一篇: 如何处理iOS 8照片扩展中的内存限制?

下一篇: 使用模块模式和实例化新对象之间的区别