What Are Methods?
Just as we can add attributes to a class, we can also add methods.
If attributes represent an object’s data, then methods represent its behavior—the actions that the object can perform.
For example, a Car class might have methods such as:
- Start the engine
- Stop the engine
- Sound the horn
- Increase speed
Adding a Method
Let’s add a method that makes the car sound its horn.
class Car { constructor(color, model) { this.color = color; this.model = model; }
// Method beepSound() { console.log("beeeeeeeeep"); }}
const car = new Car("Blue", 2020);
// Call the methodcar.beepSound();Calling a Method
After creating an object, you can call any of its methods using the dot operator (.).
car.beepSound();This tells the car object to execute its beepSound() method.
A class can contain as many methods as needed.
Why Do Methods Use Parentheses?
Notice that the method is written as:
beepSound() {}instead of:
beepSound {}That’s because every function or method in JavaScript uses parentheses ().
If a method accepts data, the parameter names are placed inside those parentheses.
For example:
drive(speed) { console.log(speed);}And it can be called like this:
car.drive(120);Is the Constructor Also a Method?
Yes.
A constructor is a special method inside a class.
The difference is that you don’t call it yourself. JavaScript automatically calls it whenever you create a new object using the new keyword.
Key Takeaways
- Methods are functions defined inside a class.
- Attributes represent data, while methods represent behavior.
- Methods are called using the dot operator (
.). - Every method is written with parentheses
(). - A constructor is a special method that runs automatically when an object is created.