0

Ok, so this is what I have:

const http = require("http");

const Server = function(){
  this.context = {};
};

Server.prototype.callback = function(req, res){
  console.log(this.context);
};

Server.prototype.listen = function(...arguments){
  const server = http.createServer(this.callback);
  return server.listen(...arguments);
};

module.exports = Server;

It logs context as undefined, but when I call the function without http.createServer it works, why and how can I fix it?

nico.user
  • 483
  • 2
  • 5
  • 15

1 Answers1

1

You need to attach the object to the callback. When you pass this.callback as an argument, it only passes the callback and there is no attachment to the object. So, when http.createServer() calls your callback, it calls the callback() method as a regular function and the object value of this is lost.

You can fix by changing this:

http.createServer(this.callback);

to this:

http.createServer(this.callback.bind(this));

This is a very common issue when passing methods as a callback. Another alternative would be this:

http.createServer(() => this.callback());
jfriend00
  • 683,504
  • 96
  • 985
  • 979