Alexander Weber
Alexander Weber

Reputation: 799

Module encapsulation with closures

In "JavaScript: The Good Parts" by Douglas Crockford there is an example for using functions and closures to encapsulate modules. According to the description below unique should contain "Q1000". I want this module pattern to work, but prefix and seq seem not to be altered, as unique yields "0" while running this example. What might be the reason?

var serial_maker = function () {
    // Produce an object that produces unique strings. A
    // unique string is made up of two parts: a prefix
    // and a sequence number. The object comes with
    // methods for setting the prefix and sequence
    // number, and a gensym method that produces unique
    // strings.
    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"

Upvotes: 0

Views: 62

Answers (1)

Paul S.
Paul S.

Reputation: 66404

You're overwriting the set_* functions, not calling them. Here are two different ways to fix it


Change to invocation

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

Using the set operator

return {
    set prefix(p) {
        prefix = p.toString();
    },
    set seq(s) {
        seq = s | 0;
    },
    gensym: function () {
        var result = prefix + seq;
        seq += 1;
        return result;
    }
};

// ...

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

Upvotes: 1

Related Questions