Q1. What is a constructor method?
A Constructor Method is a special function used to create and initialize objects in JavaScript.
It acts as a blueprint for creating multiple objects with similar properties and methods. Instead of creating objects manually, constructors help create them easily and efficiently.
It acts as a blueprint for creating multiple objects with similar properties and methods. Instead of creating objects manually, constructors help create them easily and efficiently.
Q2. How do you create a Constructor Function in JavaScript?
A constructor function is created using a regular function and is usually named with a capital letter. The new keyword is used to create objects from the constructor.
Example
Example
function Person(name, age) { this.name = name; this.age = age;}
const user1 = new Person("John", 25);console.log(user1);Explanation:
- The this keyword refers to the new object being created.
- The new keyword creates a new instance of the object.
Q3. What does the new keyword do?
The new keyword performs the following steps:
- Creates a new empty object.
- Assigns this to that object.
- Links the object to the constructor’s prototype.
- Returns the new object.
Q4. Can methods be added inside Constructor Functions?
Yes, methods can be added inside constructor functions.
Example
Example
function Car(brand, model) { this.brand = brand; this.model = model;
this.display = function() { console.log(this.brand + " " + this.model); };}
const car1 = new Car("Toyota", "Fortuner");car1.display();Q5. What happens if you forget to use the new keyword?
If the new keyword is not used, the constructor function behaves like a normal function, and this may refer to the global object or become undefined (in strict mode).
Example
This may cause unexpected behavior because the object is not created properly.
Example
function User(name) { this.name = name;}
const user = User("Mike");console.log(user);This may cause unexpected behavior because the object is not created properly.
