Classes
**
- Classes are blueprints for
- Classes provide a more formal and organized way of defining objects and their behaviour.
- A JavaScript class is not an object rather it's a template for JavaScript object.
- A class is a type of function, but instead of using the word "function " to initiate it, we use the keyword "class", and the properties are assigned inside a constructor()method.
- Class Method
- 1. Class Method are created with the same syntax as object methods.
- 2. Use the keyword class to create class.
- 3. Always add a constructor()method.
- 4. Then add any no of method.
- Example 1: Create a car class, and then create an object called "my car" based on the car class.
- Class car {
- Constructor (brand) {
- this.car name=brand;
- }
- }
- My car=new car****
- Constructor method
- Constructor method is a special method used for initializing object created with a class. It's called automatically when a new instance of the class is created. It typically assigns initial values to object properties using parameters passed to it. This ensure objects are properly initialized upon creation.
-
When a constructor is called automatically and a class is initiated, it has to have the exact name "constructor", in fact, if you do not have a constructor, JavaScript will add an invisible and empty constructor method.
-Note: A class cannot have more than one constructor() method.this will throw a syntax error.- More examples on classes.
Class person
Class student{
Constructor(rollno, name, age){
this.name=name;
this.roll No=roll No;
this.age=age;
}
}
Let student 1=new student(1,"Alex",12);
Console.log(student 1); student [name: 'Alex', roll No:1, age:12
Class product{
Constructor(name, price){
this.name= name;
this.price= price;
}
display product(){
Console.log('product:${
this.name}');
Console.log('price:${
this.price}');
}
}
Const product 1=("shirt,19.32);
Const product 2=("pant", 33.55);
**
Top comments (0)