Skip to content

Commit 4e7fc60

Browse files
committed
Design Patterns: Constructor pattern with prototypes
1 parent 936223e commit 4e7fc60

File tree

1 file changed

+37
-0
lines changed
  • Design_Patterns/The Constructor Pattern

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* The Constructor Pattern
3+
*
4+
* Constructor pattern is used to create specific types of objects.
5+
*/
6+
7+
// Basic Constructors
8+
function Car(model, year, miles) {
9+
this.model = model;
10+
this.year = year;
11+
this.miles = miles;
12+
13+
this.toString = function () {
14+
return this.model + " has done " + this.miles + " miles ";
15+
};
16+
}
17+
18+
var civic = new Car("Honda Civic", 2020, 20000);
19+
console.log(civic);
20+
console.log(civic.toString());
21+
22+
// Problems: The simple version of constructor is difficult to make inheritance, other is that functions such as toString() are redefined for each of the new object created using the Car constructor.
23+
24+
// Constructors with prototypes
25+
function Car2(model, year, miles) {
26+
this.model = model;
27+
this.year = year;
28+
this.miles = miles;
29+
}
30+
31+
Car2.prototype.toString = function () {
32+
return this.model + " has done " + this.miles + " miles ";
33+
};
34+
35+
var civic2 = new Car2("Honda Civic", 2020, 20000);
36+
console.log(civic2);
37+
console.log(civic2.toString());

0 commit comments

Comments
 (0)