javascript – Node.js不是构造函数

前端之家收集整理的这篇文章主要介绍了javascript – Node.js不是构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试使用“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)

解决方法

当你分配这个时:
exports.HttpHandlers = HttpHandlers;

您需要将其与此匹配:

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

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

exports = HttpHandlers;

然后,你的require()可以按照你这样做的方式工作:

var HttpHandlers = require('../lib/restifyHandlers/HttpHandlers');
原文链接:https://www.f2er.com/js/155821.html

猜你在找的JavaScript相关文章