I was racking my brain to make an algorithm in nodeJS work. I got a file with that function bellow where some properties are tied to this
and some functions are tied to prototype
.
function Main(controller) {
this.tipo = "string";
this.controller = controller;
this.debug = controller.debug;
this.db = controller.db;
this.util = require('util');
this.utils = require('../utils.js');
this.moment = require('moment');
}
Main.prototype.funcX = (dados) => {
// doing stuffs
}
Somehow, the properties of this
were not being recognized in functions tied to prototype
and there was always an TypeError.
Then, I've found a solution after reading this question, where I noticed that arrow function has its own this
context. Then, changing this code snippet
Main.prototype.funcX = (dados) => {
// doing stuffs
console.log(typeof this.db) // TypeError: cannot read property 'info' of undefined
};
To this
Main.prototype.funcX = function (dados) {
// doing stuffs
console.log(typeof this.db) // prints my db instance
};
made everything works well.
But I do not want to use function
keyword to these functions at all.
Q: What is the best way to use arrow functions accessing the Main's this
properties?