Javascript ES6 类变量

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

<分区>

使用 Mongoose 探索 Javascript ES6 类并在访问类变量时遇到问题。我想在 cursor.on(data) 事件中使用 this.name 引用在类的构造函数中声明的变量。我怎样才能做到这一点?

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

    }
}

最佳答案

如果您使用的是 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')
        });

    }
}

值得注意的是,这不是“类变量”,而是实例变量。

关于Javascript ES6 类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836397/

相关文章:

node.js - 使用 socket.io 发送实时分析的最佳方法

node.js - Mongodb查询文档数组字段长度而不获取数组

javascript - 函数在我的代码中不起作用

javascript - 下载 anchor 标记在浏览器中打开文件,但不在 React 组件中下载它

javascript - 使用 javascript 比较 2 个 ASCII 字符

Javascript 6 字符和空格检查

node.js - NodeJS - 为什么当前域在 Promise 中未定义?

node.js - 在 async.auto (NodeJs) 中绑定(bind) Mongoose 模型保存方法

mongodb - mongodb mapreduce 函数是否接受文档的计算值作为映射器

javascript - 需要模型的 Mongoose 错误