1

Exploring Javascript ES6 classes with Mongoose and having trouble in accessing class variables. I want to use this.name inside cursor.on(data) event referencing the variable declared in the constructor of the class. How can I achieve this??

'use strict';
const Mongo = require('../mongo')
class Example {
    constructor() {
        this.name = 'Test Class';
    }

    export(docId, callback) {
        console.log('In export' + docId);
        const cursor = Mongo.findDocById(docId);
        console.log(this.name); // Prints "Test Class"
        cursor.on('data', function (document) {
            console.log(document);
            console.log(this.name); // Prints "undefined"
        });
        cursor.on('close', function () {
            Mongo.close();
            callback(null, 'Success')
        });

    }
}
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
maddy
  • 23
  • 1
  • 5

1 Answers1

4

If you're using ES6, use ES6 arrow functions which properly preserve this context:

class Example {
    constructor() {
        this.name = 'Test Class';
    }

    export(docId, callback) {
        console.log('In export' + docId);
        const cursor = Mongo.findDocById(docId);
        console.log(this.name); // Prints "Test Class"

        cursor.on('data', document => {
            console.log(document);
            console.log(this.name); // Prints "undefined"
        });

        cursor.on('close', () => {
            Mongo.close();
            callback(null, 'Success')
        });

    }
}

It's worth noting that's not a "class variable", it's an instance variable.

tadman
  • 208,517
  • 23
  • 234
  • 262