Chapter 5, Prototype

Lets try and solve the following exercise:

Exercises

  1. Create an object called shape that has a type property and a getType() method:
            var shape = { 
              type: 'shape', 
              getType: function () { 
                return this.type; 
              } 
            }; 
    
  2. 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'; 
    
  3. To add the getPerimeter() method, use the following code:
            Triangle.prototype.getPerimeter = function () { 
              return this.a + this.b + this.c; 
            }; 
    
  4. 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.