gpt4 book ai didi

node.js - 如何在 node.js 中导出带有添加原型(prototype)方法的对象

转载 作者:搜寻专家 更新时间:2023-10-31 23:14:06 25 4
gpt4 key购买 nike

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

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 终端

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

这是一个问题,因为显然在开始扩展原型(prototype)之前调用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;

最佳答案

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

关于node.js - 如何在 node.js 中导出带有添加原型(prototype)方法的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com