Ad

What Is Happening In This Code And What Will Be The Basic Implementation Of The Following Without The "with" Keyword

- 1 answer

I was going through a code base that was creating a multi-platform package management and module system for JavaScript.

I found a path of code that was extracting from withing the function that is associated with the "exports" variable. I have attached the code snippet below, and on running the snippet you will find the "print" object gets extracted from the function. I want to know two things:-

  1. How is this code working?
  2. can this code be implemented in a more easier way without the with statement?

var context = {
  exports: {}
};

var fn = (function(args) {
  with(args) {
    return function logger() {
      exports = {
        print: function(res) {
          console.log(res);
        }
      }

    }
  }
});
fn = fn(context);
fn.call();
context.exports.print('hello World'); //Prints the hello world

Ad

Answer

First, evaluating a non-string is pointless. Remove the eval call and just use the function.

Technically, the with statement does this:

The with statement adds an object environment record for a computed object to the lexical environment of the current execution context. It then executes a statement using this augmented lexical environment. Finally, it restores the original lexical environment.

Basically, this means that when you assign an object to the identifier exports, it becomes a property of args.

Don't do this. The with statement has bad performance and is not allowed in strict mode. Just assign the property normally.

var fn = function(args) {
  return function logger() {
    args.exports = {
      print: function(res) {
        console.log(res);
      }
    }
  }
};
Ad
source: stackoverflow.com
Ad