gpt4 book ai didi

javascript - JS 函数原型(prototype)脱离上下文 Node 表达

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:59 26 4
gpt4 key购买 nike

我在带有上下文的 Node 中使用原型(prototype)时遇到问题。

/**
* 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 也会脱离上下文吗?

感谢任何帮助。

最佳答案

您可以将您的函数绑定(bind)到一个对象,这样无论它们如何被调用,this 都会如您所愿。您可以找到更多信息here .

您可以在构造函数中绑定(bind)方法。 underscore 库有一个有用的 bindAll 方法来帮助你。

关于javascript - JS 函数原型(prototype)脱离上下文 Node 表达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16854536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com