Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Crockford use this format for writing JSON.parse function?

in this JSON.parse function: 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?

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:

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.

like image 947
jmancherje Avatar asked Mar 15 '23 11:03

jmancherje


1 Answers

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.

like image 198
Amadan Avatar answered Mar 23 '23 01:03

Amadan