如何在node.js中导出添加了原型方法的对象

时间:2012-11-13 16:33:17

标签: node.js

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

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;

节点终端

尝试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;

2 个答案:

答案 0 :(得分:2)

看看这里: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()

答案 1 :(得分:1)

你正在做你的要求错误:

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

是你想要的。执行exports.Hat = Hat;时,您正在导出一个exports的对象(Hat)。因此,当您需要'./hat.js'时,您将获得该对象,并需要访问Hat属性。

来自节点repl:

> 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.owner而不是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");
}