我在文件中有一个对象,并且希望能够要求该文件,然后随心所欲地创建该对象的新实例,但我遇到了障碍。这似乎非常基本,我错过了什么。
帽子.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;
节点终端
尝试 1
> require('./hat.js');
> var mighty_duck = new Hat('Emilio');
ReferenceError: Hat is not defined
尝试 2
> var Hat = require('./hat.js');
> var mighty_duck = new Hat('Emilio');
{ owner: 'Emilio' }
> mighty_duck.tip();
TypeError: Object #<Hat> has no method 'tip'
编辑
最不幸的是,我忽略了原来是最大的问题。我试图使用的事实
util.inherits(Hat, EventEmitter);
所以我的 hat.js 实际上是
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;
这是一个问题,因为显然在开始扩展原型之前inherits
打电话很重要。修复很简单,将调用向上移动几行inherits
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;