Using classes to group similar functions together
Sunday, Aug 9, 2020
JavaScript
JavaScript
Besides creating modular objects, classes can also be used to group similar functions together. Let's say in a game, we want to calculate new position of a player as it moves forward or backward. We can wrap the two functions in a class and then call it whenever we need:
class Position{
// return new position by subtracting delta from old
newPositionReverse(x, delta = 1){
return x - delta;
}
// return new position by adding delta to old
newPositionForward(x, delta = 1){
return x + delta;
}
}
const pos = new Position();
console.log(pos.newPositionReverse(10));
// 9
console.log(pos.newPositionReverse(10, 5));
// 5
console.log(pos.newPositionForward(10));
// 11
console.log(pos.newPositionForward(10, 5));
// 15
Typically, we will not use the functions in the same file where we created these. Instead, our main program may need functions from multiple files (called modules in this context). I have updated my older note to show how it is accomplished.