Node.js <class>不是构造函数

时间:2016-09-11 03:53:52

标签: javascript node.js

我得到&#34; HttpHandlers不是构造函数&#34;尝试使用&#34; new&#34;。

尝试实例化该类时出错

正在实例化的类(../ lib / restifyHandlers / HttpHandlers):

func genericFunction<E: Equatable>(input: [(E,E)]) {
    // Need E to be Equatable for comparison
}

let someArray = [([1,2,3],[2,3,4])]

// Success on this line, even though the array is the same!
genericFunction([([1,2,3],[2,3,4])])

// Error on this line
// "Cannot convert value of type '[(Array<Int>, Array<Int>)]' to expected 
//  argument type '[(_, _)]'"
genericFunction(someArray)

拨打电话的代码:

var config = require('config');
module.exports.config = config;

var util = require('util');
var _ = require('underscore');
var EventEmitter = require("events").EventEmitter;

var HttpHandlers  = function(eventHandlers) {
    var _self = this;
    this.name = "HttpHandlers";
    if (!(this instanceof HttpHandlers)) {
        return new HttpHandlers(eventHandlers);
    }
}

util.inherits(HttpHandlers, EventEmitter);

HttpHandlers.prototype.extractHttpHandlersRequest = function(req, res, next) {
    var _self = this;
    req.locals = {};
    res.locals = {};

}
module.exports.HttpHandlers = HttpHandlers;

堆栈跟踪:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers');
var obj = new HttpHandlers(oneRouteConfig.eventHandlers);

4 个答案:

答案 0 :(得分:23)

分配时:

exports.HttpHandlers = HttpHandlers;

您需要将其与此匹配:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers').HttpHandlers;

您正在将模块的属性指定为.HttpHandlers,而不是分配整个模块,因此如果您需要该属性,则必须引用该属性。如果您希望它以其他方式工作,您可以更改为:

exports = HttpHandlers;

然后,你的require()可以像你这样做:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers');

答案 1 :(得分:3)

我收到这个错误是因为我有一些循环导入。所以这个类是未定义的..

如果它可以帮助别人!

答案 2 :(得分:1)

我在调用new ClassName();时遇到此错误,这是由于错过了“模块”而在ClassName类中引起的。来自module.exports = ClassName

以防别人像我一样愚蠢...

答案 3 :(得分:0)

就我而言,我正在使用的库中的导出操作有些奇怪。我建议尝试console.log()(或debugger;)进行任何require()的处理,然后从那里弄清楚。