Im having hard time to understand why this thing doesnt work. where is the problem? Is this the right way to pass in values to this function, are there other ways?
seqer.set_prefix = ‘Q’;
seqer.set_seq = 1000;
Is it possibleto do it in this way:
sequer.set_prefix('Q');
var serial_maker = function () {
var prefix = '';
var seq = 0;
return {
set_prefix: function (p) {
prefix = 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'; // is this the right way to pass in values to this function, are there other ways? is it possible to write like this sequer.set_prefix('Q);
seqer.set_seq = 1000; // same here?
seqer.gensym()
;
Anonymous functions are first-class citizens in JavaScript – you can generally treat them exactly like you would treat a normal function (except that they have no given identifier, unless you assign them to a name). Here’s a good tutorial about them – they are quite powerful, and I consider them to be one of the best things about JavaScript.
So yes, doing:
is incorrect. You are overwriting the funcitons with these constants. Your guess is correct – to call them, you would use:
By the way, there is another error in your function:
You’re defining an anonymous function, but calling it immediately. So unfortunately,
var serial_makerwon’t be a serial_maker – it’ll be the returned object. Of course, the subsequentvar seqer = serial_maker();will fail, because the object is not a function.