Javascript ES6类变量

时间:2017-05-07 20:32:48

标签: javascript node.js mongoose ecmascript-6 es6-class

使用Mongoose探索Javascript ES6类并且无法访问类变量。我想在this.name内部使用cursor.on(data)引用在类的构造函数中声明的变量。我怎么能实现这个?

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

    }
}

1 个答案:

答案 0 :(得分:3)

如果你正在使用ES6,使用 ES6箭头功能可以正确保存this上下文:

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

    }
}

值得注意的是,"类变量",它是一个实例变量。