class Person {
constructor(name, age, preferredFood)
{
this.name = name;
this.age = age;
this.preferredFood = preferredFood;
}
logName()
{
console.log(`The person's name is ${this.name}`);
}
}
// Create a person
let person = new Person("Joe", 25, "pizza");
// Call logName()
person.logName();
This works similarly to the previous example, but classes share their class methods between all created objects. In other words, the same single logName
function will be re-used for all created Person
objects. This solves the problem with the previous approach where a function was re-created for every object. It also uses a more convenient syntax than the alternative with prototypes (which we didn't cover).
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. However in order to focus this guide on quickly learning the basics of JavaScript, we'll move on. For now, we've just shown that if you want to create lots of objects with the same properties, the best way to do that is with class
syntax. It works similarly to using new
with a function, but classes are preferable and are how most modern JavaScript 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
- Using
new
with a function to create an object with certain properties
class
syntax as a better alternative for use with new
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 objects, functions and methods 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 MDN Web Docs links:
Part 9
When you're ready to continue, head on to the next part at Learn JavaScript in Construct, part 9: Data structures!