在Douglas Crockford的「JavaScript:The Good Parts」中,有一個使用函數和閉包來封裝模塊的例子。根據以下說明獨特應包含「Q1000」。我希望此模塊模式能夠正常工作,但前綴和seq似乎不會被更改,因爲唯一在運行此示例時會產生「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"
你覆蓋'SET_ *'功能,不稱他們。 – 2014-10-01 11:40:13