简体   繁体   中英

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

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 (eg, 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM