gpt4 book ai didi

javascript - 这两个函数的区别

转载 作者:行者123 更新时间:2023-11-30 07:41:16 25 4
gpt4 key购买 nike

在阅读“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

我的问题是:上面的和这里的这个有什么区别:

var other_serial_maker = function(pre, num){

return pre + num;

};

var makeSerial = other_serial_maker("Q", 1000);

最佳答案

如果您的目标只是生成字符串 Q1000 那么没有区别,但这不是重点。书中的示例使用闭包,因此 prefixseq 部分是私有(private)的,只能从函数内部访问。

所以我们的想法是,您可以这样做:

 var unique = seqer.gensym( ); // unique is "Q1000"

然后你可以这样做

 var anotherUnique = seqer.gensym( ); // unique is "Q1001"

因为 serial_maker 会跟踪它自己的状态,而您的代码不会。如果我们使用书中的代码,那么在设置 serial_maker 之后,我们可以根据需要多次调用 .gensym 并获得不同的结果。对于您的代码,您需要以某种方式跟踪您已经使用了哪些代码。

关于javascript - 这两个函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16753750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com