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(); 
            "triangle" 
    
  5. Loop over t showing only own properties and methods:
            for (var i in t) { 
              if (t.hasOwnProperty(i)) { 
                console.log(i, '=', t[i]); 
             } 
            } 
    
  6. Randomize array elements using the following code snippet:
            Array.prototype.shuffle = function () { 
              return this.sort(function () { 
                return Math.random() - 0.5; 
              }); 
            }; 
    

    Testing:

            > [1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle(); 
             [4, 2, 3, 1, 5, 6, 8, 9, 7] 
            > [1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle(); 
             [2, 7, 1, 3, 4, 5, 8, 9, 6] 
            > [1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle(); 
             [4, 2, 1, 3, 5, 6, 8, 9, 7] 
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243