为什么Crockford使用这种格式编写JSON.parse函数?

时间:2021-08-07 20:16:51

in this JSON.parse function: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js

在这个JSON.parse函数中:https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js

Why does crockford choose to declare so many functions in his variable declarations and then separate 1 function and then return a main function at the end?

为什么crockford选择在他的变量声明中声明这么多函数然后将1个函数分开然后在结尾处返回一个main函数?

Is there benefit to writing a function like this:

编写这样的函数有什么好处:

pseudo syntax:

var json_parse = (function () {
    var x,
        y, 
        z, 
        string = function () {
             <code>
        },
        word = function () {
             <code>
        },
        white = function () {
             <code>
        },
        value;

    value = function () {
        <code>
        white();
        string();
        etc..
    };
    return function (string) {
         return something;
    }
})();

vs writing a function like this:

vs写一个这样的函数:

var parse_json = function (input) {
     var x, y, z;

     function string () {
           <code>
     }
     function word () {
           <code>
     }
     function white () {
           <code>
     }
     function value () {
         <code>
          white();
          string();
          etc..
     }

    function mainParse () {
         return something;
    }

   return mainParse(input);

};

Hopefully my little code examples make sense. I am new to JavaScript and I want to make sure I learn the best practices or writing large functions like this.

希望我的小代码示例有意义。我是JavaScript的新手,我想确保我学习最佳实践或编写像这样的大型函数。

1 个解决方案

#1


7  

Your variant would have to create word, white... functions each time one invokes json_parse. His way lets him create them once and capture them in a closure, so that they are accessible to him but not to anyone else outside his function.

每次调用json_parse时,您的变体都必须创建word,white ...函数。他的方式让他创造了一次并将它们捕获在一个封闭物中,这样他们就可以使用它们,但不能让他接触到其他人以外的任何人。

#1


7  

Your variant would have to create word, white... functions each time one invokes json_parse. His way lets him create them once and capture them in a closure, so that they are accessible to him but not to anyone else outside his function.

每次调用json_parse时,您的变体都必须创建word,white ...函数。他的方式让他创造了一次并将它们捕获在一个封闭物中,这样他们就可以使用它们,但不能让他接触到其他人以外的任何人。