2

I am trying to reproduce some code from the book "Javascript: The Good Parts" by Douglas Crockford. The idea is to use closures for object encapsulation and avoid Javascript's inherent global variables.

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"

Chrome is picking up the error:

Uncaught TypeError: Property 'serial_maker' of object [object DOMWindow] is not a function (anonymous function)

What am I doing wrong?

EDIT: I should say this code is entirely copy and pasted from the book...

3 Answers 3

8

You are trying to execute the result of a function as a function, and are assigning values to functions. Try:

var seqer = serial_maker;
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym();

Also see this jsFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help. It's really strange, this faulty code (I found it too in the original (2008) book) from Crockford.
1

There are two errors in this code example:

  1. The definition of serial_maker is finished with () which invokes the anonymous function. That makes the next line:

    var seqer = serial_maker();
    

    erroneous since serial_maker is not the function but the object returned by the anonymous function.

  2. Once the previous error is fixed the two lines:

    seqer.set_prefix = 'Q';
    seqer.set_seq = 10000;
    

    should change to:

    seqer.set_prefix('Q');
    seqer.set_seq(10000);
    

(Source: http://oreilly.com/catalog/errata.csp?isbn=9780596517748&order=date)

Comments

1

I am currently working through the book and I see a redundant pair of parentheses () in your posted code, when I compare it to the book. You have:

        }
    };
}(  );

it should be:

        }
    };
};

Along with, the additional answers where the 'Q' and the 1000 need to be wrapped in ().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.