souparno majumder
souparno majumder

Reputation: 2052

what is happening in this code and what will be the basic implementation of the following without the "with" keyword

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

Upvotes: 1

Views: 105

Answers (1)

Oriol
Oriol

Reputation: 288100

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);
      }
    }
  }
};

Upvotes: 2

Related Questions