这两个函数的差

Difference between these two functions

本文关键字:函数 两个      更新时间:2023-09-26

在阅读"Javascript the Good Parts"时,在"module"一章中看到了这段代码。

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部分是私有的,只能从函数内部访问。

思路是,你可以这样做:

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

然后你可以这样写

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

因为serial_maker跟踪它自己的状态,而您的代码没有。如果我们使用书中的代码,那么在设置serial_maker之后,我们可以随心所欲地调用.gensym,并得到不同的结果。对于代码,您需要以某种方式跟踪已经使用过的代码。

主要区别在于外部function作用域包含prefixseq的声明,因此它们被包含在一个闭包中,该闭包将跟随seqer对象。

换句话说,书中的示例返回一个带有状态的对象,而您的示例是一个普通函数(不使用任何状态)。

serial_maker的意义在于它以seq的方式存储每个串行生成器的状态,以确保任何一个都不会产生重复的状态。如果前缀是不同的,那么在串行制造商之间也不会有重复的前缀。