You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// The Prototype Pattern is a design pattern in JavaScript that allows objects to inherit properties and methods from other objects, known as prototypes.
3
+
// It promotes code reuse and helps conserve memory by allowing objects to share common properties and methods through inheritance.
4
+
5
+
6
+
// We will see two example:
7
+
// 1. using simple object
8
+
9
+
varperson={
10
+
greet: function(){
11
+
return"Hello, my name is "+this.name;
12
+
}
13
+
};
14
+
varperson1=Object.create(person);
15
+
person1.name="Bittu";
16
+
17
+
varperson2=Object.create(person);
18
+
person2.name="Rajesh";
19
+
20
+
console.log(person1.greet());// Hello, my name is Bittu
21
+
console.log(person2.greet());// Hello, my name is Rajesh
22
+
23
+
24
+
//2. using constructor function
25
+
functionCar(make,model,year){
26
+
this.make=make;
27
+
this.model=model;
28
+
this.year=year;
29
+
}
30
+
Car.prototype.displayInfo=function(){
31
+
return`This is a ${this.year}${this.make}${this.model}.`;
32
+
};
33
+
34
+
varcar1=newCar("Toyota","Camry",2020);
35
+
varcar2=newCar("Honda","Civic",2018);
36
+
37
+
console.log(car1.displayInfo());// This is a 2020 Toyota Camry.
38
+
console.log(car2.displayInfo());// This is a 2018 Honda Civic.
0 commit comments