开发者

Does Node.js require inheritance?

开发者 https://www.devze.com 2023-02-18 02:28 出处:网络
In my server.js file I included the Underscore.js library. var _ = require(\'underscore\') I have my routes like this:

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 intellige开发者_JS百科nt way to do this?


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


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


As far as I know Node.js engine "requires/charges" a module/file.js in a different scope (I don't know exactly how), for security reasons (imagine a module could change the variables were it's required. That would be dangerous! More information about this concern: Information hiding).

The only exception are global Node.js objects that are exposed into the module scope.

A global object is, precisely the object "global", and everything you define without var keyword actually is added to that global object:

foo_var = "Whatever"

means that:

console.log(global.foo_var) // Logs "Whatever"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号