user3818284
user3818284

Reputation:

Can I use require() in Node.js in a prototypical way?

I've been interested in prototypical programming with JavaScript, and I'm trying to figure out an efficient way of doing it with Node modules.

For example, I'd like to use a prototype to quickly create a debug object in each of my modules, which has a name property and a log method, constructed via:

custom_modules/debug.js

var settings = require('custom_modules/settings');

exports = function debug(name){

    this.name = name;
    this.log = function(message){

        if (settings.debug == 'true'){

             console.log("[Debug][" + name + "]: " + message);

        }

    }

}

So I'd like to know if I can use that module as a constructor, like so:

do_something.js

var debug = new require('custom_modules/debug')("Something Doer");

debug.log("Initialized"); // -> [Debug][Something Doer] : Initialized

Will it work? If not, what's the correct equivalent?

Upvotes: 0

Views: 57

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

new doesn't care where the function comes from. So yes, the function can be the result of requireing a module.

However, the module must directly export the function. In your current code you are merely assigning a new value to the local exports variable, and we all know that assigning to a local variable doesn't have any effect outside of its scope.

The module will still export an empty object. You have to override the exports property of the module:

module.exports = function() {...};

As pointed out, there will be problems with precedence, so you would have to do

var debug = new (require('custom_modules/debug'))("Something Doer");

Upvotes: 1

Related Questions