JS函数原型脱离上下文节点表达
JS function prototype out of context node express
我有一个问题使用原型节点与上下文
/**
* 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");
});
}
};
};
相关文章:
- 将函数的上下文应用于javascript变量
- 节点导出返回一个空对象
- 可以前端maven插件使用节点,npm已经安装
- 在jstree中,如何将指定的节点集中到大型树上
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 如何从模块链中调用函数.导出到节点中
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 使用JSTree上下文菜单捕获新创建的节点
- D3 上下文菜单,更改所选节点颜色
- 是节点.js一次只执行一个上下文
- 将上下文菜单(context.js)附加到cytoscape.js中的节点
- 节点Webkit窗口上下文
- 花式树:在右键单击上下文菜单中获取节点
- jsTree上下文菜单获取选定的节点id
- 将上下文传递到交互式节点外壳导致“;类型错误:沙箱参数mus已转换为上下文;
- Web音频离线上下文和分析器节点
- 在jQuery中使用带有上下文节点的子选择器的新方法是什么?
- JS函数原型脱离上下文节点表达
- 传递节点模块的上下文
- 节点JavaScript上下文共享内置原型