Welcome back, JavaScript enthusiast! We're diving back into JavaScript classes, focusing on constructors
and class methods
. Picture building a robot: Constructors are the initial settings, and class methods are the commands that enable it to perform actions. Are you ready for a refresher? Let's get started!
A JavaScript class serves as a blueprint for creating objects. Here's a basic class, Robot
:
As of now, this Robot
class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, attributes and methods are needed.
A constructor
is a special method that initializes an object when it is created. In JavaScript, this method is always named constructor
and is called automatically during object creation. It sets up the initial states of the new object.
If you do not define a constructor
method in your class, JavaScript will provide an empty constructor method automatically.
Here, we upgrade the Robot
class with a constructor
:
In this case, the constructor
method gets automatically called when we create a new Robot
instance, set with name
and color
attributes. It's always good practice to use constructors like constructor
to ensure each instance starts with the correct initial values.
Having one constructor is great, but what if we want more flexibility in setting up our robots? That's where default parameters come into play and give us something similar to multiple constructors.
Here's a default color for our robots:
With default parameters, color
becomes optional. When we don't specify it, the robot is 'grey' by default.
Class methods are akin to commands controlling the robot's actions. They provide additional behaviors for our objects.
This Robot
class allows the robots to introduce themselves:
The sayHello
method allows our robot instance to interact and even communicate.
Sometimes, you might want to alter the attributes of your class instances or fetch their values. You can accomplish this by creating methods to set or get these attributes.
Here’s how you can add methods to change the name
and color
of the robot, as well as retrieve them:
The setName
and setColor
methods allow changing the name
and color
of the robot after it has been created. The getName
and getColor
methods enable retrieving these values when needed.
Great job! You've refreshed and deepened your understanding of JavaScript classes, constructors
, and class methods
, and learned how to mimic multiple constructors. Additionally, you saw how to add methods that can update and retrieve class attributes. Now, you can breathe more life into your JavaScript classes, making them more versatile and powerful. Next, we'll move on to hands-on tasks where you'll apply these concepts to more complex scenarios. Keep up the good work!
