lundi 30 mars 2015

ES6 methods get a null "this" and class variables are inaccessible

I'm using an ES6 class to bundle some functionality together in Node. Here's (basically) what it looks like:



class processDocs {
constructor(id) {
this.id = id;
}

getDocs(cb) {
docs
.query(qb => {
qb.where('id', this.id);
})
.fetch()
.then(function(documents) {
cb(null, documents);
})
;
}

alterDocs(documents, cb) {
//some logic
}

reindexSearch(cb) {
//some logic
}

process() {
async.waterfall([
this.getDocs,
this.alterDocs,
this.reindexSearch
]);
}
}


export default processDocs;


I thought that with ES6 classes, the way to assign public variables was to simply reference this and the way to initialize those variables via a constructor is exactly how it shows up in my class definition.


Here's how I'm calling the class (in a separate file):



var Processor = require('./processDocs');

var pr = new Processor(id);
var docs;
pr.process();


Here's the issue, when I console.log out this from the constructor, I get my { id: id } value as predicted; however, whenever I log out this in getDocs when process is running, it's null. BUT, when I log out this in process() right before the waterfall, I get my original object.


Is there any reason for this?


Btw, I'm using node: v0.10.33 and babel-node 4.6.6 and I run babel-node with the --harmony flag. Before anyone asks, I can't update to a newer Node version due to a major dependency which is stuck at v0.10.x.


Aucun commentaire:

Enregistrer un commentaire