I have an object in a file and want to be able to require that file and then create new instances of the object at whim, but I’ve hit a snag. This seems so incredibly basic, what am I missing.
hat.js
function Hat(owner) {
this.owner = owner;
}
Hat.prototype.tip = function() {
console.log("and he (" + owner + ") tipped his hat, just like this");
}
exports.Hat = Hat;
node terminal
Attempt 1
> require('./hat.js');
> var mighty_duck = new Hat('Emilio');
ReferenceError: Hat is not defined
Attempt 2
> var Hat = require('./hat.js');
> var mighty_duck = new Hat('Emilio');
{ owner: 'Emilio' }
> mighty_duck.tip();
TypeError: Object #<Hat> has no method 'tip'
Edit
I, most unfortunately, left out what turned out to be the biggest problem bit. The fact that I was trying to use
util.inherits(Hat, EventEmitter);
So my hat.js would actually be
function Hat(owner) {
this.owner = owner;
}
Hat.prototype.tip = function() {
console.log("and he (" + owner + ") tipped his hat, just like this");
}
util.inherits(Hat, EventEmitter);
exports.Hat = Hat;
This is an issue, because, apparently it is important to have your inherits call before you start extending the prototype. The fix is simple, move the inherits call up a few lines
function Hat(owner) {
this.owner = owner;
}
util.inherits(Hat, EventEmitter);
Hat.prototype.tip = function() {
console.log("and he (" + owner + ") tipped his hat, just like this");
}
exports.Hat = Hat;
You are doing your require wrong:
Is what you want. When you do
exports.Hat = Hat;you are exporting an object (exports) with a propery ofHat. So when you require'./hat.js'you get the object, and need to access theHatproperty.From node repl:
Of course that was causing an error since you said
ownerand notthis.ownerintip(), but after I changed that it worked fine 🙂If you want to just do
Then change your export to:
And it works:
EDIT Cleaned up and inherits from EventEmitter: