JS函数原型脱离上下文节点表达

JS function prototype out of context node express

本文关键字:节点 上下文 函数 原型 JS      更新时间:2023-09-26

我有一个问题使用原型节点与上下文

/**
 * Constructor.
 * 
 * @param   object  opts        The options for the api.
 * @param   object  config      The application's configuration.
 * @param   object  db          The database handler.
 * @return  void
 */
var clientModel = function ( opts, config, db )
{
    this.opts = opts;
    this.config = config;
    this.db = db;
};
/**
 * Get a list of items.
 * 
 * @param   function    cb  Callback function.
 * @return  void
 */
clientModel.prototype.getList = function( cb )
{
    this.db.query(
        "SELECT FROM " + this.db.escape("client"),
        function ( err, rows, fields )
        {
            if( err.code && err.fatal )
            {
                cb(
                {
                    message: "SQL error locating client."
                });
                return;
            }
            if(! rows.length )
            {
                cb(
                {
                    message: "Unable to locate client."
                });
                return;
            }
            cb( false, rows, fields );
        });
};
/**
 * Default http request for getting a list of items.
 * 
 * 
 * @param   object  req     The http request.
 * @param   object  res     The http response.
 * @return  void
 */
clientModel.prototype.httpGetList = function ( req, res )
{
    this.getList( function ( err, rows, fields )
    {
        res.end("Got a list");
    });
}

// - Append model to output.
module = module.exports = clientModel;

基本上节点express框架调用httpGetList和"this"没有getList由于"this"是由于上下文表达,是否有任何方法来改进我的代码,以便正确地做到这一点,我猜如果它得到了这个。那么this。db也会脱离上下文吗?

感谢您的帮助。

您可以将函数绑定到对象,这样无论如何调用它们,this都将如您所期望的那样。你可以在这里找到更多信息。

可以在构造函数中绑定这些方法。下划线库有一个有用的bindAll方法来帮助您。

我建议您在模块内创建实例,并导出处理请求的函数。

/**
 * Exports.
 * 
 * @param   object  opts        The options for the api.
 * @param   object  config      The application's configuration.
 * @param   object  db          The database handler.
 * @return  void
 */
module = module.exports = function ( opts, config, db )
{
    var instance = new clientModel( opts, config, db );
    return {
        /**
         * Default http request for getting a list of items.
         * 
         * 
         * @param   object  req     The http request.
         * @param   object  res     The http response.
         * @return  void
         */
        httpGetList : function ( req, res )
        {
            instance.getList( function ( err, rows, fields )
            {
                res.end("Got a list");
            });
        }
    };
};