[英]Difference between these two functions
While reading "Javascript the Good Parts", came across this bit of code in the "module" chapter. 在阅读“ Javascript the Good Parts”时,在“模块”一章中遇到了这段代码。
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;
console.log(result);
seq += 1;
return result;
}
};
};
var seqer = serial_maker( );
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym( ); // unique is "Q1000
My question is: whats the difference between the above and this bit here: 我的问题是:以上内容与此处的区别是什么?
var other_serial_maker = function(pre, num){
return pre + num;
};
var makeSerial = other_serial_maker("Q", 1000);
If you only objective to to generate the string Q1000
then no difference, but that's not the point. 如果您仅打算生成字符串Q1000
则没有区别,但这不是重点。 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. 书中的示例使用闭包,因此prefix
和seq
部分是私有的,只能从函数内部访问。
So the idea is, you can do this: 因此,您可以执行以下操作:
var unique = seqer.gensym( ); // unique is "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. 因为serial_maker
会跟踪其自身的状态,所以您的代码不会。 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. 如果我们使用本书中的代码,那么在设置serial_maker
我们可以根据需要多次调用.gensym
并获得不同的结果。 With your code, you'd need to somehow keep track of which codes you've used already. 使用您的代码,您需要以某种方式跟踪已使用的代码。
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. 主要区别在于外部function
范围包含prefix
和seq
的声明,因此它们包含在将跟随seqer
对象的闭包中。
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). 换句话说,本书中的示例返回一个带有状态的对象,而您的示例是一个普通函数(不使用任何状态)。
The point of serial_maker is that it stores state in seq for each serial maker that ensures any one won't produce duplicates. serial_maker的要点在于,它为每个串行制造者将状态存储在seq中,以确保任何人都不会产生重复。 Provided the prefixes are distinct, there won't be duplicates across the serial makers either. 如果前缀是不同的,那么序列制造商之间也不会重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.