Giallo Giallo - 1 month ago 5
Javascript Question

Cannot read property of undefined issue on callback

I have a very simple class that is wrapping a node.js serial port class. On object creation, a new logger is created. When stepping through, everything seems fine - when I call open, I can see that the logger is a valid logger object. However, when the error method is triggered by an error on opening the port, the logger is no longer defined - it seems there's some issue with callbacks and the created object, but I have no idea what? Thanks for the help!

EDIT: I wrote the class in TypeScript, and I'm realizing this is probably a super annoying, classic JavaScript "this" issue...I apologize - I'm pretty new to js.

"use strict";
var SerialPort = require('serialport');
const logger = require('../logger');
class MySerialPort {
constructor() {
this.log = new logger();
}

error(error) {
console.log(error);
try {
this.log.log('Serial port error: ' + error);
}
catch (e) {
console.log(e);
}
}

open(commport) {
this.port = new SerialPort(commport);
this.port.on('data', this.dataRecieved);
this.port.on('error', this.error);
return true;
}

dataRecieved(data) {
console.log(data.toString());
}
}
module.exports = MySerialPort;

Answer

use an arrow function or bind this, either way should work

this.port.on('error', (err) => {this.error(err)});

or

var error=this.error.bind(this);
this.port.on('error', error);