Magician Magician - 10 days ago 6
Javascript Question

Javascript function callback variable scope

I am trying to pass an object variable to a callback

var sql = require('mssql');
var asset_update = function (connection, addr) {
this.connection = connection;
this.addr = addr;
this.addr_long = parseInt(addr, 16);
}

asset_update.prototype.getFromMac = function () {
var ps = new sql.PreparedStatement(this.connection);
ps.input('addr', sql.Binary);
ps.prepare('SELECT asset_id FROM asset_addr WHERE addr = @addr', function (err) {
ps.execute({ addr: this.addr_long }, function (err, recordset) {
ps.unprepare();
console.log(recordset.length);
console.log(this.addr_long);
})
});
}


How can I pass this.addr_long to the ps.execute() callback?

Answer

You can use an arrow function to preserve this :

ps.prepare('SELECT asset_id FROM asset_addr WHERE addr = @addr', (err) => {
    ps.execute({ mac: this.addr_long }, function (err, recordset) { //this has been preserved
        ps.unprepare();
        console.log(recordset.length);
        console.log(this.addr_long);
    })
});

Check out this doc for the ES5 alternatives, which you shouldn't use anymore.

A popular one would be to rename this to that or self. But this is now obsolete. It would look like :

var self = this;
ps.prepare('SELECT asset_id FROM asset_addr WHERE addr = @addr', function (err) {
        ps.execute({ mac: self.addr_long }, function (err, recordset) {
            ps.unprepare();
            console.log(recordset.length);
            console.log(that.addr_long);
        })
    });

As you're new to node/JS, I suggest you read the following resources :

What does "this" mean?

Callbacks overview and tricks