无法在javascript中实例化对象(node.js)

嗨有人可以告诉我为什么我不能实例化下面的类/对象?

function Arbitrage(odds1, odds2, investment) { this.investment = investment; this.odds1 = odds1; this.odds2 = odds2; this.arbPercent = function() { return 1.0/this.odds1 + 1.0/this.odds2; }; this.profit = function() { return this.investment / this.arbPercent() - this.investment; }; this.individualBets = function() { return { odds1bet : this.investment/this.odds1/this.arbPercent(), odds2bet : this.investment/this.odds2/this.arbPercent() }; }; }; module.exports = Arbitrage; 

我这样称呼它:

 var utility = require('../businesslogic/utility'); ... router.post('/calculate', function(req, res) { var arbit = new utility.Arbitrage(req.body.odds1, req.body.odds2, req.body.investment); res.json({ arbPercentage : arbit.arbPercent(), profit : arbit.Profit(), indvBets : arbit.individualBets() }); }); 

第一行, var arbit = new utility.Arbitrage(...)抛出错误。 它说TypeError: undefined is not a function

我已经检查过,该utility不是null或类似的东西。 也所有的构造函数参数都可以。

我不是很熟悉JavaScript,任何帮助将不胜感激。 谢谢。

您直接导出您的Arbitrage类,所以在您需要之后

 var utility = require('../businesslogic/utility'); 

utility实际上是您的Arbitrage类,意思是typeof utility === 'function'

我可以看到修复它的两种方法。

1.改变你要求你的Arbitrage类的方式:

 var Arbitrage = require('../businesslogic/utility'); // ... var arbit = new Arbitrage(...); 

2.或者改变你输出的方式:

 exports.Arbitrage = Arbitrage; 

这是因为你导出它的方式

你应该使用:

 module.exports.Arbitrage = Arbitrage; 

然后你可以这样instanciate:

 var Arbitrage = require('../businesslogic/utility'); var varbitrage = new Arbitrage();