What are classes?
Classes are a template for creating objects. Use the keyword class to create a class.
Always add a method named constructor()
Creating a new class
class Car{
constructor(brand, model, color){
this.brand = brand;
this.model = model;
this.color = color;
this.sold = false;
}
carSold(){
this.sold = true;
}
}
We create a class with the class keyword and then create the constructor function.
The constructor function immediately gets invoked when we create an object using this class.
You might notice that there is a function
carSold(){
this.sold = true;
}
Which is actually in the ES6 syntax. Normally, you'd see this function written like:
this.carSold = function(){
this.sold = true;
}
Creating an object with the class
Now as you're done creating the class, time to create an object with it.
To do this you need to type in:
let <object_name> = new <class_name>(<parameters>)
For example, for the class stated above:
let car1 = new Car('Toyota','Sienna','Blue')'
This would create an object car1 of Brand: Toyota, Model: Sienna and Color: Blue.
Here, the parameters inside the round brackets are passed to the constructor and thus sets the Brand to Toyota, Model to Sienna and Color to Blue.
Initially its sold status is set to false.
This is changed by calling the carSold() function.
So if you call car1.carSold() - the value of car1.sold will be true
Top comments (0)