Simplifying Workflows, Maximizing Impact
Call at: 07850 074505
Using a arrow function or a normal method appears to be the same things particularly when our background is to do with previous programming languages generations.
New languages like typescript have moved the boundaries further when it comes to refactoring capabilities and the power of strict types data structures.
let’s take 2 examples demonstrating the issue:
const colors = {
color: 'red',
printColor() {
console.log(this.color)
}
}
From the snippet above, we may perform both calls below and see both return the value ‘red’
console.log(colors.color)
colors.printColor()
The problem comes when we call the method by reference
fc = colors.printColor
fc()
The code above will fail to perform due to an error of undefined object. The latter undefined error will be due to the scope of the method not being the colors
object and that means the code 'this'
fails
To resolve the problem, the simple fix consists in calling an arrow version of the same method
fc = () => {
colors.printColor()
}
fc()