1

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?

laukok
  • 47,545
  • 146
  • 388
  • 689
  • 2
    It's not about the class, is about how you pass the function and how the caller calls it. `this` is dynamic with or without classes. You need to bind `polygon` to the function, like `app.get(..., polygon.log.bind(polygon))` – elclanrs Jul 17 '16 at 07:23
  • 2
    @elclanrs - This question is not a duplicate of that question. There is no mention of this situation at all in that other question. Those answers may cover the solution to this question, but that does not make one question a dup of the other. It makes it a useful reference, but not a duplicate question. – jfriend00 Jul 17 '16 at 07:48

2 Answers2

1

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));
undefined
  • 136,817
  • 15
  • 158
  • 186
1

In the first case you are directly passing the function hence you wont get this as the polygon object

Use

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

In the second case you are using

p.log('world')

here log function will be called and this would be the polygon.

Piyush.kapoor
  • 6,041
  • 1
  • 17
  • 18