avasin
avasin

Reputation: 9726

Why `exports` is referencing same object as `this` in nodejs module?

Today i found very strange way of using exports... This is code of separate nodejs module, that reproduces it.

Guys assign values to this scope, which is equal to exports variable. How do they achieved that exports=this?

(function() {

  this.Test = (function(){

    function Test() {
      this.name = 'Test 1';
    }

    return Test;

  })();

  // Will output Test { name: 'Test 1' }
  console.log(new exports.Test);

  // Will output { Test: [Function: Test] }
  console.log(exports);

}).call(this);

Upvotes: 0

Views: 40

Answers (1)

EmptyArsenal
EmptyArsenal

Reputation: 7464

In node, exports is very similar to the window object in the DOM where window.foo would be equivalent to this.foo, when used in the global scope.

In this case, exports is essentially this of the entire module. When you use .call(this), you're essentially manually setting the this value of the anonymous function to the this value of the module, AKA the global scope object.

Thus, this in the call is referencing the global scope, the anonymous function is bound to the global this, and exports is equivalent to the global this.

You code is equivalent to this:

this.Test = (function(){

  function Test() {
    this.name = 'Test 1';
  }

  return Test;
})();

// Will output Test { name: 'Test 1' }
console.log(new exports.Test);

// Will output { Test: [Function: Test] }
console.log(exports);

Upvotes: 1

Related Questions