Skip to content

Commit 24af2a4

Browse files
committed
prototype pattern
1 parent 6e365d2 commit 24af2a4

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
1+
// prototype pattern
2+
// 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+
var person = {
10+
greet: function() {
11+
return "Hello, my name is " + this.name;
12+
}
13+
};
14+
var person1 = Object.create(person);
15+
person1.name = "Bittu";
16+
17+
var person2 = 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+
function Car(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+
var car1 = new Car("Toyota", "Camry", 2020);
35+
var car2 = new Car("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.
139

0 commit comments

Comments
 (0)