Skip to content

Commit b073b40

Browse files
committed
Added constructor pattern examples
1 parent 8e3a4c0 commit b073b40

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

constructor.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Examples from The Illusion of Class by Ryan Kinal
3+
4+
http://blog.javascriptroom.com/2013/01/29/the-illusion-of-class/
5+
*/
6+
7+
// Construcors are just functions
8+
var Point = function(x, y)
9+
{
10+
this.x = x;
11+
this.y = y;
12+
}
13+
14+
// Put "methods" on the prototype property of the function
15+
Point.prototype.translate = function(x, y)
16+
{
17+
this.x += x;
18+
this.y += y;
19+
}
20+
21+
// Use the "new" keyword to create a new object
22+
// with a prototype equal to Point.prototype
23+
var point = new Point(17, 42);
24+
point.translate(5, 6);
25+
26+
/*
27+
I loves me some inheritance!
28+
*/
29+
var Point3d = function(x, y, z)
30+
{
31+
Point.call(this, x, y);
32+
this.z = z;
33+
}
34+
35+
Point3d.prototype = new Point();
36+
// OR
37+
Point3d.prototype = Object.create(Point.prototype); // probably better
38+
39+
Point3d.prototype.translate = function(x, y, z)
40+
{
41+
Point.prototype.translate.call(this, x, y);
42+
this.z += z;
43+
}
44+
45+
var point3d = new Point3d(19, 20, 21);
46+
point3d.translate(4, 5, 6);

0 commit comments

Comments
 (0)