javascript - nodejs在回调函数中绑定(bind)对象

标签 javascript node.js callback

这是我尝试过的。

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/

相关文章:

javascript - 使用 window.onerror 报告客户端错误的最佳实践?

javascript - Rxjs 嵌套订阅与多个内部订阅

javascript - 读取 Json 对象数组并创建 csv 文件时,第一列是从第二条记录开始的

android - 只有在另一个类中完成使用 Parse.com 的异步数据导入后,才在 Android 中填充 ListView

c++ - 使用回调中的值更新 std::vector 的 GUI slider 的动态数量

javascript - 使用工厂作为 Angular 数据表中的源数据不起作用

javascript - 使用 ngRepeat 的复杂嵌套行表

javascript - Range header 是压缩字节还是未压缩字节的大小(以字节为单位)?

node.js - 如何发送外部文件,只使用 url(https ://. ....)

javascript - Javascript自定义 Highcharts 方法