teelou teelou - 1 year ago 52
Node.js Question

ES6 class behaves differently in ExpressJS?

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

With expressJS


class Polygon {

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

var output = {
publicKey :publicKey,
query: query

export {Polygon as default}


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

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

Without expressJS


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

export { Polygon as default}


import Polygon from 'Polygon';

var p = new Polygon();


How can I get
undefined to return
Polygon {}
in expressjs?

Answer Source

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));