Search code examples
javascriptesprima

Javascript Object from External file, program


I am so confused about JavaScript's object system. I know that everything is considered Object in JavaScript but in this code of Esprima, I don't see any statement to declare this project to be accessed with esrpima like the following line: (https://github.com/ariya/esprima/blob/master/esprima.js)

var syntax = esprima.parse(text);

My question is how and where to define something like esprima.parse(text) in Javascript so that it can be exported as external package and be accessed with the object name. I know how to define object like Object = {a: "B"}; but can't find a way to figure this out. Please help me!

(function (root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.esprima = {}));
    }
}(this, function (exports) {
    'use strict';

    var Token,
        TokenName,
 ...

Solution

  • That's because it doesn't. The variable name, esprima, comes from code that includes esprima. For example:

    var esprima = require('esprima');
    esprima.parse(text);
    

    You could give the variable any other name:

    var foo = require('esprima');
    foo.parse(text);
    

    All the the esprima.js file does is define an object which is exported. It does not dictate the name of the variable to which the object is assigned to eventually.


    If the script is loaded in a browser, it actually does define esprima explicitly. You can see it in line 55:

     factory((root.esprima = {}));
    

    This creates an object and assigns it to root.esprima. But it's also a function call, so the object is passed to factory, which is the function defined in 57, which accept a parameter exports. This is where the code assigns all the properties to.