Organizing Functions into Objects and Classes
Sometimes, it makes sense to organize functions into member functions of objects and classes. These concepts will be addressed in greater detail in Chapter 4, Classes and Objects, but for now we can examine how we take a function declaration and add it to an object or class.
Let's take a simple function:
Example_OrganizingFuncs_1.ts
1 function addTwoNumbers(a: number, b: number) { return a + b; }
If we wanted to have an object that contains a number of math functions, we could simply add the following function to it:
2 const mathUtils = { 3 addTwoNumbers 4 }; 5 6 console.log(mathUtils.addTwoNumbers(3, 4));
Link to the preceding example: https://packt.link/qX1QO
The output is as follows:
7
Note that the syntax used in the mathUtils
object is shorthand, meaning the left and right side of the assignment are the same. This could also be written like this:
Example_OrganizingFuncs_2.ts
5 const mathUtils...