Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Node.js require inheritance?

In my server.js file I included the Underscore.js library.

var _ = require('underscore')

I have my routes like this:

// require routes
require('./routes/document');

In the document route, I want to use Underscore.js. But it seems like the _ variable is not inherited/inside the document scope. Does that mean I have to set the _ variable on every single required route? Or is there a more intelligent way to do this?

like image 666
Harry Avatar asked Mar 18 '11 06:03

Harry


People also ask

Does Node js support inheritance?

By default, each class in Node. js can extend only a single class. That means, to inherit from multiple classes, you'd need to create a hierarchy of classes that extend each other.

What is inheritance in Node js?

inherits is a function of Node. js that is in the util module. In util. inherit , the constructor inherits the prototype methods from one to another.

What require does in Node js?

1) require() 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.

Is there inheritance in JavaScript?

In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.


2 Answers

Yes, you should set the _ in the files that needs it to be available.

Alternatively, you can put it in the global scope by removing the var part.

_ = require('underscore');
require('./routes/document'); // _ will be visible in document as well
like image 51
Decko Avatar answered Oct 06 '22 19:10

Decko


Check the Node.js module documentation where require() is thoroughly explained.

http://nodejs.org/docs/v0.4.5/api/modules.html

As for your specifics:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Hence, if you require('underscore') in both your parent library and './routes/document', only one instance of the underscore module will be loaded and hence. Both variables will be in fact the same object.

And by the way, you don't want to define variables in the global scope as it might generates side effects and potentially overwrite properties in other modules.

Finally, the util module provides an inherits method to subclass another constructor and inherit from its prototypes.

http://nodejs.org/docs/v0.4.5/api/util.html#util.inherits

like image 40
pdeschen Avatar answered Oct 06 '22 19:10

pdeschen