I am using a method wich belongs to a module as a callback in a function from my server.
From this method, i need to access an array encasulated in the module (MyArray).
I can't use this since it refers to the original function (someFunction in my example).
But i don't understand why i can't use the that: this feature in this case (that is undefined).
MyModule.js
module.exports = {
MyArray: [],
that: this,
test: functiion() {
//How to access MyArray ?
}
};
server.js
var MyModule = require('MyModule');
someFunction(MyModule.test);
this.MyArray works.
MyModule.test is bound to a this equal to module.exports
You can also just use local variables inside your module.
var MyArray = [];
module.exports = {
test: function() {
// MyArray is accessible
}
};
And you could also use module.exports.MyArray.
You can use bind to bind the this you want to that function so that even when it's used as a callback the this is correct:
MyModule.js
module.exports = {
MyArray: []
};
module.exports.test = (function() {
console.log(this.MyArray); // works here even when not called via MyModule.test
}).bind(module.exports);