Lets try and solve the following exercise:
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(); "triangle"
Loop over
t
showing only own properties and methods:for (var i in t) { if (t.hasOwnProperty(i)) { console.log(i, '=', t[i]); } }
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]