0

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,
 ...
  • 1
    Please see my answer below. I'm not sure if I fully understood your question. Let me know if something is unclear or I missed anything. – Felix Kling Mar 10 '14 at 01:40

1 Answers1

0

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks a lot! I get this, but is "require" the only way to do this? Because in the code I only see the lines with "require" /*global esprima:true, YUI:true, require:true */ and require(['custom/editor'], function (editor) { which doesn't really seem related –  Mar 10 '14 at 02:07
  • And when calling I am not using any require function.function Esprima(text, oid) { var syntax = esprima.parse(text); document.getElementById(oid).innerHTML = JSON.stringify(syntax); } –  Mar 10 '14 at 02:08