In this article, we are going to discuss How to Define a Class With Properties and Methods in JavaScript?. This is the frequently asked and opening question in JavaScript coding interviews for beginners, and this is also a simple and good question to start the interview. So let’s discuss a little answer for that.
Solution:
To define a class, we just need to use ‘class’ keyword. Also, it must consist of a constructor to add properties and methods. Let’s see the code to understand in deep:
<script>
class Car{
constructor(name, model){
this.name = name;
this.model = model;
}
start(){
console.log(`The Car name is ${this.name} and model is ${this.model}`);
}
}
bwm = new Car("Sports Edition", 630);
bmw.start();
</script>
Okay, so we made a simple class named car, also remember class can be unnamed as well. So as we know we should create a constructor with some properties like here we have name and model. Then we assign these two properties to private property, here we need this keyword to make private property, and its scope will be limited to class Car. Also, we added a method named start, here we just added a simple console.log().
Now to use the class, and its elements, we have to make an object like any other object made. To create a bmw object, we need to use a new keyword, and we have to pass a number of arguments required in the constructor. Here we require two arguments to assign in properties, now we can access values and methods from class using object bmw. And we are just accessing and calling start() method where we have a simple code to show.
Output
The Car name is Sports Edition and model is 630