I am trying to understand why "this" can be undefined in classes sometimes, and how to fix it. I have read other answers on this but I guess what I'm asking is a solution. I read a lot of open source code because it helps me learn. Every time I see a class, the code just uses this all the way through. Whenever I try to make a class and call this in a callback function, it is undefined. I have used var that = this as a solution but it's causing some issues and I figure this is something I should have figured out a while ago.
Here's an example
class myClass {
constructor(ping) {
this.run()
this.ping = ping
}
run() {
console.log(this.ping)
//This is defined here
request({
url: 'https://test.com',
method: 'get'
},
function (err, res, body) {
this.ran(body)
//"ran" is not a function
})
}
ran(body) {
console.log(body)
}
}
Any input is appreciated!