Node.js <Class>不是一个构造函数

尝试使用“new”实例化该类时,出现“HttpHandlers不是构造函数”错误。

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

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); 

堆栈跟踪:

 2016-09-10T23:44:41.571-04:00 - [31merror[39m: Sun, 11 Sep 2016 03:44:41 GMT Worker #master: exiting from error: TypeError: HttpHandlers is not a constructor TypeError: HttpHandlers is not a constructor at setupRestifyRoute (/usr/apps/das/src/myrepo/nodejs/myapp/lib/router.js:78:14) at Router.setup_routes (/usr/apps/das/src/myrepo/nodejs/myapp/lib/router.js:40:3) at /usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:222:14 at initialize (/usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:38:9) at setup_server (/usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:107:4) at /usr/apps/das/src/myrepo/nodejs/myapp/bin/server.js:275:4 at /usr/apps/das/src/myrepo/nodejs/myapp/node_modules/temp/lib/temp.js:231:7 at FSReqWrap.oncomplete (fs.js:123:15) 

       

网上收集的解决方案 "Node.js <Class>不是一个构造函数"

当你分配这个:

 exports.HttpHandlers = HttpHandlers; 

你需要用这个匹配:

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

你正在分配你的模块的属性是.HttpHandlers ,不分配整个模块,所以如果你想要那个属性,你必须引用属性。 如果你想以另一种方式工作,你可以改变为:

 exports = HttpHandlers; 

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

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

在导出调用中你省略了modulemodule.exports.HttpHandlers