Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does require work with new operator in node.js?

Let's have a file.js with this code:

module.exports.func = function(txt) {
    this.a = 1;
    this.b = 2;
    console.log(txt, this);
    return this;
}

Now we have another JS file where we do following:

var r1 = new (require('./file')).func('r1');
var r2 = new require('./file').func('r2');

In r1 case it works as intended - r1 contains reference to the newly created object.

In r2 case it does not work - r2 gets reference to module.exports from within the file.js.

The intention was to create a new object by calling func() constructor. Sure, I can do it also this way which is equal to r1:

var r3 = require('./file');
var r4 = new r3.func('r1');

However, I do not understand why r2 does not behave the same way as r1.

How do the extra parenthesis around require('./file') make a difference?

like image 906
Pavel Lobodinský Avatar asked Jul 11 '13 22:07

Pavel Lobodinský


People also ask

How does require work in NodeJS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What does require (' express ') do?

require('express') returns a function reference. that function is called with express() . app is an object returned by express().

How does require work NPM?

require() is used to consume modules. It allows you to include modules in your app. You can add built-in core Node. js modules, community-based modules (node_modules), and local modules too.

What is the result of calling the require function?

As you can see, the require function returns an object, the keys of which are the names of the variables/functions that have been exported from the required module ( circle ). In short, the require function returns the module. exports object.


1 Answers

These two versions are fundamentally different.

This one:

new (require('./file')).func('r1');

Executes the require, returning the exports of ./file and then calling the new operator on the results .

This one:

var r2 = new require('./file').func('r2');

Invokes require as a constructor.


Let's look at a more isolated and simple example:

new Date() // creates a new date object
new (Date()) // throws a TypeError: string is not a function
like image 131
Benjamin Gruenbaum Avatar answered Oct 11 '22 07:10

Benjamin Gruenbaum