这是我尝试过的。
var obj = {sfsf: fsdfs};
connection.query("UPDATE table SET `qty` = `qty` - ? WHERE item_id = ?", [p1, p2], callback.bind(obj))
回调函数:
function callback(f_err, f_rows, f_fields){ //default parameters err, rows, fields
if(!f_err){
console.log(obj); //undefined
// other lines of code
}
}
我怀疑我的做法是错误的。查询执行后会传递一些默认参数,例如err、rows、fields
。使用这些参数,我想将一些数据传递给回调函数。还有其他方法可以做到这一点吗?
最佳答案
小引用
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
因此,在您的情况下,在回调 obj
中绑定(bind)为 this
。因此,您必须将 console.log(obj)
更改为 console.log(this)
。
您可以在 MDN 找到更多信息
关于javascript - nodejs在回调函数中绑定(bind)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781283/