在" JavaScript:好的部分"作者Douglas Crockford有一个使用函数和闭包来封装模块的例子。根据以下描述, unique 应包含" Q1000"。我想要这个模块模式工作,但前缀和 seq 似乎不会被改变,因为 unique 会产生" 0"在运行此示例时。可能是什么原因?
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"
答案 0 :(得分:1)
您正在覆盖set_*
个功能,而不是调用它们。以下是两种不同的修复方法
更改为调用
var seqer = serial_maker();
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym(); // unique is "Q1000"
使用set
运算符
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"