本文介绍了Node.js对象不是函数 - module.exports的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我为node.js app创建的模块。该应用程序也使用socket.io,我想在创建它时将socket.io对象传递给拍卖对象。

I have a module I created for a node.js app. The app also uses socket.io and I want to pass the socket.io object into the auction object when I create it.

当我在Node之外这样做时,这是有效的,但在里面,我得到错误'对象不是一个函数' - 我的猜测是它与module.exports有关,但我确定它会是什么。

This works when I do it outside of Node, but inside, I get the error 'object is not a function' - my guess is it has to do with the module.exports, but I'm sure what it would be.

任何建议都很棒 - 谢谢!

Any suggestions would be awesome - thank you!

auction.js

auction.js

var Auction = function(socket) {
    this.data      = [];
    this.timer     = null;
    this.socket    = socket;
}

Auction.prototype = {

    add: function(auction) {
        this.data.push(auction);
    }
}


module.exports.Auction = Auction;

server.js:

server.js:

var  Auction          = require('./lib/auction');

var auctions = new Auction(socket);




推荐答案

您正在导出一个属性为<$ c的对象$ c>拍卖

You are exporting an object with 1 property Auction

当您需要模块时,您导入的对象看起来像

When you required the module, you imported an object which looks like

{
  Auction: function(){...}// Auction function
}

因此要么只导出函数:

module.exports = Auction;

或在您需要模块时参考酒店:

or reference the property when you require the module:

var  Auction = require('./lib/auction').Auction;

默认情况下,module.exports是一个空对象: {}

By default, module.exports is an empty object : {}

您可以用函数替换 exports 。这将导出该函数。

You can replace exports with a function. This will export just that function.

或者您可以导出许多函数,变量,对象,方法是将它们分配给 exports 。这就是您在问题中所做的事情:将函数拍卖分配给拍卖 >出口

Or you can export many functions, variables, objects, by assigning them to exports. This is what you have done in your question: assigned the function Auction to the property Auction of exports.

这篇关于Node.js对象不是函数 - module.exports的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:05