0

Why is the class member undefined after definitely being assigned a value in constructor?

main.js:

import { createServer } from "http";
class DefaultHandler {
    handle(i, o) {
        console.log("entered handler");
        o.end(() => {
            console.log("ended");
        });
    }
}
class Gateway {
    handler;
    constructor() {
        this.handler = new DefaultHandler();
        if (this.handler !== undefined)
            console.log("handler instantiated");
    }
    handleTraffic(i, o) {
        console.log("gateway got traffic");
        this.handler.handle(i, o);
    }
}
const server = createServer(new Gateway().handleTraffic);
server.listen({ port: 28751 }, () => {
    console.log(`listening on ${Object.values(server.address()).join(":")}`);
});

then, while also curling localhost:28751, STDOUT is:

$ node --version && node main.js
v16.14.2
handler instantiated
listening on :::IPv6:28751
gateway got traffic
file:///main.js:19
        this.handler.handle(i, o);
                     ^

TypeError: Cannot read properties of undefined (reading 'handle')
    at Server.handleTraffic (file:///main.js:19:22)
    at Server.emit (node:events:526:28)
    at parserOnIncoming (node:_http_server:951:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
jka
  • 337
  • 5
  • 15
  • 1
    When you pass `new Gateway().handleTraffic` to the server, this 'detaches' the `this` context for `handleTraffic` so that it no longer references the gateway instance. Please see [how to access the correct this inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – CRice May 19 '22 at 17:07
  • Basically, pass a fully scope-qualified function `() => new Gateway().handleTraffic()` rather than passing the bare function reference `new Gateway().handleTraffic`. – Mike 'Pomax' Kamermans May 19 '22 at 17:11

0 Answers0