<分区>
使用 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')
});
}
}