4

我在文件中有一个对象,并且希望能够要求该文件,然后随心所欲地创建该对象的新实例,但我遇到了障碍。这似乎非常基本,我错过了什么。

帽子.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;
4

2 回答 2

4

看看这里: http: //openmymind.net/2012/2/3/Node-Require-and-Exports/

你可以试试这个:

function Hat(owner) {
    this.owner = owner;
}
Hat.prototype.tip = function() {
    console.log("and he (" + this.owner + ") tipped his hat, just like this");
}
module.exports = Hat;

然后…… 像这样:

var hat = require('./hat.js');
var mighty_duck = new hat('Emilio');
mighty_duck.tip()
于 2012-11-13T16:40:51.860 回答
2

你做错了你的要求:

var Hat = require('./hat.js').Hat;

是你想要的。当您这样做时,exports.Hat = Hat;您正在导出一个exports具有Hat. 因此,当您需要'./hat.js'获取对象时,需要访问该Hat属性。

从节点复制:

> require('./hat.js');
{ Hat: [Function: Hat] }
> require('./hat.js').Hat;
[Function: Hat]
> var Hat = require('./hat.js').Hat;
undefined
> var mighty_duck = new Hat('Emilio');
undefined
> mighty_duck.tip();
and he (Emilio) tipped his hat, just like this

当然,这导致了一个错误,因为你说owner而不是this.ownerin tip(),但是在我改变它之后它工作正常:)

如果你只想做

var Hat = require('./hat.js'),
    hat = new Hat('Emilio');

然后将您的导出更改为:

module.exports = exports = Hat;

它有效:

> require('./hat.js');
[Function: Hat]
> var Hat = require('./hat.js');
undefined
> var hat = new Hat('Emilio');
undefined
> hat.tip();
and he (Emilio) tipped his hat, just like this

编辑清理并从 EventEmitter 继承:

var util = require('util'),
    events = require('events');

var Hat = exports.Hat = function(owner) {
    events.EventEmitter.call(this);
    this.owner = owner;
}

util.inherits(Hat, events.EventEmitter);

Hat.prototype.tip = function() {
    console.log("and he (" + this.owner + ") tipped his hat, just like this");
}
于 2012-11-13T16:35:34.713 回答