Web Technologies Unit-2
Constructors in JavaScript:
What is a Constructor?
A constructor is a special function used to create and initialize objects.
It acts as a blueprint for creating multiple objects with similar structure and behavior.
In JavaScript, constructor functions are usually written with a capitalized name (e.g., `Student`,
`Car`).
Key Features:
Constructor functions are called using the `new` keyword.
The `this` keyword refers to the new object being created.
Can define properties and methods for each new object.
Syntax of a Constructor Function
function Person(name, age) {
[Link] = name;
[Link] = age;
[Link] = function() {
return "Hi, I'm " + [Link];
};
}
Creating an Object:
let p1 = new Person("Chandu", 25);
[Link]([Link]()); // Output: Hi, I'm Chandu
Example 1 – Student Constructor
function Student(name, rollNo) {
[Link] = name;
[Link] = rollNo;
}
let s1 = new Student("Ravi", 101);
let s2 = new Student("Priya", 102);
[Link]([Link]); // Output: Ravi
[Link]([Link]); // Output: 102
Department of CSM AITAM, TEKKALI
Web Technologies Unit-2
Constructor with Method
function Rectangle(width, height) {
[Link] = width;
[Link] = height;
[Link] = function() {
return [Link] [Link];
};
}
let rect = new Rectangle(10, 5);
[Link]([Link]()); // Output: 50
Difference Between Normal Function and Constructor
Feature Normal Function Constructor Function
Used for Executing code Creating objects
Call using Just function name `new` keyword
Naming Any case PascalCase (usually)
this Refers to global or calling context Refers to the new object
ES6 Class Syntax (Modern Way)
class Employee {
constructor(name, id) {
[Link] = name;
[Link] = id;
}
show() {
return `Employee: ${[Link]}, ID: ${[Link]}`;
}
}
let emp1 = new Employee("Sita", 201);
[Link]([Link]()); // Output: Employee: Sita, ID: 201
Department of CSM AITAM, TEKKALI