Chapter 5, Prototype
Lets try and solve the following exercise:
Exercises
- Create an object called
shape
that has atype
property and agetType()
method:var shape = { type: 'shape', getType: function () { return this.type; } };
- The following is the program for a
Triangle ()
constructor:function Triangle(a, b, c) { this.a = a; this.b = b; this.c = c; } Triangle.prototype = shape; Triangle.prototype.constructor = Triangle; Triangle.prototype.type = 'triangle';
- To add the
getPerimeter()
method, use the following code:Triangle.prototype.getPerimeter = function () { return this.a + this.b + this.c; };
- Test the following code:
> var t = new Triangle(1, 2, 3); > t.constructor === Triangle; true > shape.isPrototypeOf(t); true > t.getPerimeter(); 6 > t.getType(); ...
Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.