Q1. What is a class in JavaScript?
A class in JavaScript is a blueprint used to create objects. It allows developers to define properties and methods that the objects created from the class will have.
Classes were introduced in ES6 (ECMAScript 2015) to make object-oriented programming easier and more structured.
Before classes, JavaScript used constructor functions to create objects. Classes provide a cleaner and more readable syntax.
Example
Classes were introduced in ES6 (ECMAScript 2015) to make object-oriented programming easier and more structured.
Before classes, JavaScript used constructor functions to create objects. Classes provide a cleaner and more readable syntax.
Example
class Person { constructor(name, age) { this.name = name; this.age = age; }
greet() { return "Hello, my name is " + this.name; }}
const user = new Person("John", 25);console.log(user.greet());Q2. What is the constructor() method in a JavaScript class?
The constructor() method is a special method that is automatically called when an object is created from a class. It is mainly used to initialize object properties.
Each class can have only one constructor method. If you do not define one, JavaScript automatically creates an empty constructor.
Example
Each class can have only one constructor method. If you do not define one, JavaScript automatically creates an empty constructor.
Example
class Car { constructor(brand) { this.brand = brand; }}
const car1 = new Car("BMW");console.log(car1.brand);Q3. How do you create an object from a class?
An object is created using the new keyword followed by the class name.
The new keyword creates a new instance of the class and calls the constructor automatically.
Example
The new keyword creates a new instance of the class and calls the constructor automatically.
Example
class Animal { constructor(type) { this.type = type; }}
const dog = new Animal("Dog");console.log(dog.type);Q4. Can JavaScript classes have methods?
Yes, JavaScript classes can have methods. Methods are functions defined inside a class that describe object behavior.
Example
Example
class Calculator { add(a, b) { return a + b; }}
const calc = new Calculator();console.log(calc.add(5, 3));Q5. What is class inheritance in JavaScript?
Inheritance allows one class to acquire properties and methods from another class using the extends keyword.
The class that inherits is called the child class, and the class being inherited is called the parent class.
Example
The class that inherits is called the child class, and the class being inherited is called the parent class.
Example
class Animal { speak() { return "Animal makes sound"; }}
class Dog extends Animal {}
const d = new Dog();console.log(d.speak());