gpt4 book ai didi

javascript - Node.js 不是构造函数

转载 作者:IT老高 更新时间:2023-10-28 23:22:52 26 4
gpt4 key购买 nike

我在尝试使用“new”实例化该类时收到“HttpHandlers is not a constructor”错误。

类被实例化(../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)

最佳答案

当你分配这个时:

exports.HttpHandlers = HttpHandlers;

您需要将其与此匹配:

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

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

exports = HttpHandlers;

然后,您的 require() 可以像您这样工作:

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

关于javascript - Node.js <Class> 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432687/

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