Giallo Giallo - 1 year ago 36
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) {
try {
this.log.log('Serial port error: ' + error);
catch (e) {

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

dataRecieved(data) {
module.exports = MySerialPort;

Answer Source

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

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


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