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;