Skam
Skam

Reputation: 7808

Node Modules and Prototype Inheritance

Currently I have:

index.js (in module foo)

function Foo(options) {
    this.memberVar = options.memberVar;
}

Foo.prototype.bar = function(word) {
    console.log('word: ', word);
}

module.exports = Foo;

server.js (in separate module bar)

var Foo = require('foo'),
    foo = new Foo(options),
    greeting = 'Hello World!';

foo.bar(greeting); // prints Hello World!

This is nice and all but I feel it could be prettier and easier for others to understand if I didn't have to use the new keyword to instantiate a new foo object to expose its member functions.

So here's what I would like to be able to do:

var greeting = 'Hello World!',
    foo = require('foo')(options);
foo.bar(greeting); // prints Hello World!

How do I modify my current foo - index.js to be able to access the Foo object as described in the code snippet above?

Upvotes: 1

Views: 70

Answers (1)

KeatsPeeks
KeatsPeeks

Reputation: 19347

If you don't want the consumers of the module to use new, you can expose a factory method :

// index.js (in module foo)

function Foo(options) {
    this.memberVar = options.memberVar;
}

Foo.prototype.bar = function(word) {
    console.log('word: ', word);
}

module.exports = function(options) {
    return new Foo(options);
}


// server.js (in separate module bar) 

var greeting = 'Hello World!',
    foo = require('foo')(options);
foo.bar(greeting); // prints Hello World!

Please note, however, than it could greatly confuse the users of your module. Your original pattern is widely accepted and is the preferred way of exposing a constructor.

Upvotes: 1

Related Questions