Node.js< Class>不是构造函数 [英] Node.js <Class> is not a constructor

查看:85
本文介绍了Node.js< Class>不是构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用new实例化该类时,我得到HttpHandlers不是构造函数错误。

I'm getting "HttpHandlers is not a constructor" error when trying to instantiate that class using "new".

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

Class being instantiated (../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);

Stacktrace:

Stacktrace:

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 ,不分配整个模块,所以如果你想要那个属性,你必须引用该属性。如果你想让它以另一种方式工作,你可以改为:


You are assigning a property of your module to be .HttpHandlers, not assigning the whole module so if you want that property, you have to reference the property. If you want it to work the other way, you could change to this:

exports = HttpHandlers;

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

And, then your require() could work the way you are doing it like this:

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

这篇关于Node.js< Class>不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆