Javascript JS函数原型上下文外节点表达
我在有上下文的节点中使用原型时遇到问题Javascript JS函数原型上下文外节点表达,javascript,node.js,oop,Javascript,Node.js,Oop,我在有上下文的节点中使用原型时遇到问题 /** * 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 clien
/**
* 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;
基本上,node express框架调用httpGetList,而“this”没有getList,因为“this”是由上下文表示的,是否有任何方法改进我的代码以正确执行此操作,我猜如果它到达this.getList,那么this.db也将脱离上下文
非常感谢您的帮助。我建议您在模块内创建实例,并导出处理请求的函数
/**
* 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");
});
}
};
};
您可以将函数绑定到对象,这样无论如何调用它们,
这将是您所期望的。你可以找到更多的信息
可以在构造函数中绑定方法。下划线库有一个有用的bindAll方法来帮助您实现这一点。您需要使用clientModel的实例->使用new
我在模块外部执行,基本上我在该文件外部创建一个模型实例,然后使用“.get”将其分配给express。“var model=new clientModel();server.get(“/path”,model.httpGetList)”并且当express调用请求时,出于某种原因它会释放上下文。