I am reading a node.js book that is a couple of years old. There is an example that it creates a middleware from scratch, to add messages to a session variable.
This is the code from the book, the middleware
const express = require('express');
const res = express.response;
res.message = function(msg, type){
type = type || 'info';
var sess = this.req.session;
sess.messages = sess.messages || [];
sess.messages.push({ type: type, string: msg });
};
I guess the this
here reffers to the res.message
? If I console log the this
from the function, then I get a huge ServerResponse
like this :
ServerResponse {
domain: null,
_events: { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
a lot more lines...
If I try to convert it to an anonymous arrow function, like so
res.message = (msg, type)=>{
type = type || 'info';
var sess = this.req.session;
sess.messages = sess.messages || [];
sess.messages.push({ type: type, string: msg });
};
then I get TypeError: Cannot read property 'session' of undefined
Since the this
is lexically bound in arrow functions, maybe I dont need the this
at all
res.message = (msg, type)=>{
type = type || 'info';
var sess = res.req.session;
sess.messages = sess.messages || [];
sess.messages.push({ type: type, string: msg });
};
and again I get TypeError: Cannot read property 'session' of undefined
. If I console log the res
inside the function, I get a different ServerResponse
like this
ServerResponse {
status: [Function: status],
links: [Function],
send: [Function: send],
json: [Function: json],
a lot more lines
So , how can I convert the function, to an anonymous arrow function? And what's with the this
? Where does it point to?
(the book is "Node.js in Action" by Mike Cantelon, Marc Harter, T.J. Holowaychuk and Nathan Rajlich, ©2014 by Manning Publications, chapter 9.1.2)
Thanks