Module (JS the good parts)

A module is a function or object that presents an interface but that hides its state and implementation. The module pattern takes advantage of function scope and closure to create relationships that are binding and private.

The general pattern of a module is a function that defines private variables and functions; creates privileged functions which, through closure, will have access to the private variables and functions; and that returns the privileged functions or stores them in an accessible place. For example, if we want to make an object that produces a serial number:

    var serial_maker = function(){
        var prefix ='';
        var seq = 0;
        return {
            set_prefix: function(p){
                prefix = String(p);
            },
            set_seq: function(s){
                seq = s;
            },
            gensym: function(){
                var result = prefix + seq;
                seq += 1;
                return result;
            }
        };
    };

    var seqer = serial_maker();
    seqer.set_prefix = ('Q');
    seqer.set_seq = (1000);
    var unique = seqer.gensym(); // unique is "Q1000"

The methods do not make use of this or that. As a result, there is no way to compromise the seqer. It isn’t possible to get or change the prefix or seq except as permitted by the methods. The seqer object is mutable, so the methods could be replaced, but that still does not give access to its secrets. seqer is simply a collection of functions, and those functions are capabilities that grant specific powers to use or modify the secret state.