souparno majumder
souparno majumder

Reputation: 2052

what is the meaning of the following function syntax in nodejs?

I encountered the following function call in a nodejs project.

var setEnv = function(envCtor) {
  if (typeof envCtor == 'string') {
    envCtor = ({
      node: ENV_node
    })[envCtor];
  }

  ENV = new envCtor({
    foo: foo,
    bar: bar
  });
  this.__env = ENV;
  this.__dir = ENV.getCwd();
};

function ENV_node() {
  //some code
};

setEnv('node');

I don't get the syntax, can anybody help me to understand whats going in this function ? TIA

Upvotes: 0

Views: 83

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

I would first like to understand what envCtor = ({ node: ENV_node })[envCtor]; is doing

Having determined that envCtor is a string, it's setting it to either:

  • ENV_node (if envCtor is "node"), or
  • A standard object property (e.g., any of the ones on Object.prototype) if envCtor is "toString", "valueOf", etc., or
  • undefined

(I couldn't guarantee that they did that second one intentionally, given what they do with envCtor later. :-) toString isn't a constructor function.)

The way it's doing that is by creating an object with one "own" property, node, and then the usual set of inherited properties, then looking up the value of the property whose name matches the envCtor string. Here's a version split into its parts:

var tempObj = {node: ENV_node};
var newValue = tempObj[envCtor];
envCtor = newValue;

The reason for the () is to avoid confusion with creating a block rather than an object with {node: ENV_node}. However, there's no real need for them and they could be removed. The parser won't treat the { as the beginning of a block, as it appears on the right-hand side of an assignment operator.

Example:

var ENV_node = "the ENV_node value";
function test(envCtor) {
    var before = envCtor;
    envCtor = { node: ENV_node }[envCtor];
    console.log(before + " -> " + envCtor);
}
test("node");
test("toString");
test("foo");

Upvotes: 4

Related Questions