teelou teelou - 4 months ago 12
Node.js Question

ES6 class behaves differently in ExpressJS?

Why does a class behave differently in ExpressJS? For an example:

With expressJS

lib/Polygon.js:

class Polygon {

log (req, res) {
var publicKey = req.params.publicKey;
var query = req.query;
console.log(this); // undefined

var output = {
publicKey :publicKey,
query: query
};
res.send(output);
}
}

export {Polygon as default}


app.js:

import express from 'express';
import Polygon from './lib/Polygon';

var polygon = new Polygon();
app.get('/input/:publicKey', polygon.log);


Without expressJS

lib/Polygon.js:

class Polygon {
log(req, res) {
console.log(this); // Polygon {}
}
}

export { Polygon as default}


app.js:

import Polygon from 'Polygon';

var p = new Polygon();

p.log('world')


How can I get
console.log(this);
undefined to return
Polygon {}
in expressjs?

Answer

In the second code snippet the log function is called as a member of the p object and this is why this refers to the object. This is not the case in the first code snippet as you are passing the method to another function and the method is detached from the object. You can explicitly set the this value by using bind method:

app.get('/input/:publicKey', polygon.log.bind(polygon));
Comments