nodejs中的模块函数/类的实例

时间:2017-08-08 13:36:50

标签: javascript node.js ecmascript-6 ecmascript-5 multiple-instances

我有一个以ES5.1开头的项目,后来我改为支持ES6,所以我使用了async-await,让...

现在我需要具有类似实例的模块/对象。

我发现this帖子解释了这个过程,但是......

当我这样做时:

'use strict';

let _ = require('lodash');
var mappings;

function SafeRequestHandler(reqMappings) {

    if (!(this instanceof SafeRequestHandler)) {
        return new SafeRequestHandler((reqMappings));
    }

    mappings = reqMappings;
}

function safeHandleReq(req, res) {
    try {
        let pair = _.find(mappings, {'url': req.url});
        return pair.handler(req, res);
    } catch (err) {
        console.log(err);
    }
}

SafeRequestHandler.prototype.safe = safeHandleReq;

module.exports = SafeRequestHandler;

但现在,每次我这样做:

var handler = require('../util/safeRequestHandler');

let handlerMappings = [
    {
        url: def.party_create,
        handler: partyCreate
    },
    {
        url: def.party_modify,
        handler: partyModify
    },
    {
        url: def.party_get,
        handler: partyGet
    }
];

var handle = new handler(handlerMappings).safe;

我在this.mappings中得到SafeRequestHandler替换,例如。它不是一个实例。

所以我尝试了ES6方法来定义处理程序:

'use strict';

let _ = require('lodash');

class SafeRequestHandler {

    constructor(reqMappings) {
        this.mappings = reqMappings;
    }

    safeHandleReq(req, res) {
        try {
            let pair = _.find(this.mappings, {'url': req.url});
            return pair.handler(req, res);
        } catch (err) {
            console.log(err);
        }
    }

}

并将其实例化为:

let handlerMappings = [
    {
        url: def.party_create,
        handler: partyCreate
    },
    {
        url: def.party_modify,
        handler: partyModify
    },
    {
        url: def.party_get,
        handler: partyGet
    }
];

let handle = new SafeRequestHandler(handlerMappings).safeHandleReq;

..但是这样我甚至无法在mappings中与safeHandleReq(...)联系。 this未定义,mappings未定义

我认为我只是不完全理解基本原则,所以请你纠正并解释这两种方法有什么问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果将method特定类实例存储到变量中,您将丢失上下文。

// handle doesn't have a pointer to its context (aka, this)
let handle = new SafeRequestHandler(handlerMappings).safeHandleReq;
// so handle() will output cannot read property mappings of undefined

将其更改为:

const instance = new SafeRequestHandler(handlerMappings);

const handle = (...args) => instance.safeHandleReq(...args);

此处的详细信息:Losing "this" context in JavaScript when passing around members

答案 1 :(得分:0)

您的第一个代码会创建一个全局变量,因此只需一个值。你也可以在那里使用 this

 let _ = require('lodash');
function SafeRequestHandler(reqMappings) {
  if (!(this instanceof SafeRequestHandler)) {
    return new SafeRequestHandler((reqMappings));
  }
   this.mappings = reqMappings;
}

SafeRequestHandler.prototype.safeHandleReq =  function(req, res) {
    try {
        let pair = _.find(this.mappings, {'url': req.url});
        return pair.handler(req, res);
    } catch (err) {
        console.log(err);
    }
}
module.exports = SafeRequestHandler;