Difference Between These Two Functions
Solution 1:
If you only objective to to generate the string Q1000
then no difference, but that's not the point. The example from the book is using a closure so that the prefix
and seq
parts are private and only accessible from within the function.
So the idea is, you can do this:
var unique= seqer.gensym( ); //uniqueis "Q1000"
And then you can do this
var anotherUnique = seqer.gensym( ); // unique is "Q1001"
Because the serial_maker
keeps track of it's own state, which your code does not. If we use the code from the book, then after setting up the serial_maker
we could call .gensym
as many times as we wanted and get a different result. With your code, you'd need to somehow keep track of which codes you've used already.
Solution 2:
The main difference is that the outer function
scope contains a declaration of prefix
and seq
, so they are contained in a closure that will follow the seqer
object around.
In other words, the example from the book returns an object with a state whereas your example is a plain function (that doesn't use any state).
Solution 3:
The point of serial_maker is that it stores state in seq for each serial maker that ensures any one won't produce duplicates. Provided the prefixes are distinct, there won't be duplicates across the serial makers either.
Post a Comment for "Difference Between These Two Functions"