Why Do Classes Need Attributes?
So far, our classes have been very simple—they only executed code inside the constructor.
In real applications, however, objects need to store data.
For example, a car might have information such as:
- Color
- Model year
- Manufacturer
- Speed
These pieces of information are called attributes (or properties).
Adding Attributes to a Class
Let’s modify our Car class so that it accepts a color and a model year.
class Car { constructor(color, model) { this.color = color; this.model = model; }}
const car = new Car("Blue", 2020);
console.log(car.color);console.log(car.model);How Does the Constructor Receive Data?
Notice the constructor definition:
constructor(color, model);The values inside the parentheses are called parameters. They represent the data that the constructor expects when a new object is created.
When creating the object, we provide those values:
const car = new Car("Blue", 2020);In this example:
"Blue"becomes the value ofcolor.2020becomes the value ofmodel.
What Does this Mean?
The keyword this is one of the most important concepts in Object-Oriented Programming.
When we write:
this.color = color;we’re saying:
this.coloris the object’s own property.coloris the value received by the constructor.
In other words, we’re copying the incoming value into the object itself.
The same idea applies here:
this.model = model;What Does the Dot (.) Mean?
You’ve probably noticed that JavaScript uses the dot (.) very often.
The dot operator simply means:
Access something that belongs to another object.
For example:
console.log("Hello");Here:
consoleis an object.logis a method that belongs to that object.
The same applies to our own object:
car.color;We’re accessing the color property inside the car object.
Likewise:
car.model;accesses the model property.
Key Takeaways
- Attributes are the data stored inside an object.
- Constructors receive data through parameters.
thisstores those values inside the object.- The dot operator (
.) is used to access properties and methods that belong to an object. - You can access any property using the syntax
object.property.