// Create three different instances of the 'Person' class
const person1 = new Person("Joe", 25, "pizza");
const person2 = new Person("Jenny", 30, "noodles");
const person3 = new Person("Maya", 20, "burrito");
// Call methods on each instance in turn
person1.logDetails();
person2.logDetails();
person3.logDetails();
It's been quite a jump from objects to classes. However classes are fundamental to object-oriented programming, and essential when interacting with both Construct and the browser built-in features. It's important to be familiar with them, even as a beginner.
Other features
Classes have many more features. However we won't go in to any more detail on them here. If you want to dig deeper in to them, take a look at Classes on MDN for the JavaScript side of things, and Classes in the TypeScript Handbook for the reference on TypeScript's handling of classes. However in order to focus this guide on quickly learning the basics of TypeScript, we'll move on. For now, we've just shown that if you want to create lots of objects with the same properties and methods, the best way to do that is with class
syntax. Classes are how most object-oriented TypeScript code is written.
Conclusion
In this part we've covered;
- Using functions in object properties, also known as methods
- The shorthand syntax for methods (also used in classes)
- How
this
refers to the object the method was called on
- How arrow functions handle
this
differently, in a way that is often useful
- Adding a "click" event handler that runs a function whenever something happens
- The
class
syntax to define a set of object properties and methods, including a special constructor
method
- Using the
new
keyword to create objects from a class
That's all we need to cover regarding objects and functions for now, which together have been covered by the past four parts of this guide. However it's well worth the time to get familiar with them, as they are all are fundamental parts of programming. It's hard to get anything serious done without them! In the next part we'll move on to some other data structures that are useful for programming, such as arrays.
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following links: