这两个功能之间的区别 [英] Difference between these two functions

查看:41
本文介绍了这两个功能之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读"Javascript the Good Parts"时,在模块"一章中遇到了这段代码.

While reading "Javascript the Good Parts", came across this bit of code in the "module" chapter.

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);

推荐答案

如果仅打算生成字符串 Q1000 ,则没有区别,但这不是重点.本书中的示例使用闭包,因此 prefix seq 部分是私有的,只能从函数内部访问.

If you only objective to to generate the string Q1000 then no difference, but that's not the point. 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.

因此,您可以执行以下操作:

So the idea is, you can do this:

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

然后您可以执行此操作

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

因为 serial_maker 会跟踪其自身的状态,而您的代码不会.如果我们使用本书中的代码,则在设置 serial_maker 之后,我们可以根据需要多次调用 .gensym ,并获得不同的结果.使用您的代码,您需要以某种方式跟踪已经使用过的代码.

Because the serial_maker keeps track of it's own state, which your code does not. 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. With your code, you'd need to somehow keep track of which codes you've used already.

这篇关于这两个功能之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆