Prototype demo

This demo shows how to extend an object definition. In the new method called sum(), note the difference between length (a property with parentheses) and sum() (a method with parentheses) WARNING: some advise against extending Array. For more informaiton, see http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype For more on extending the Array object, see http://stackoverflow.com/questions/11337849/ways-to-extend-array-object-in-javascript

by Brian von Konsky

JavaScript

MyArray = function () {
    this.description = undefined;  // add a new property
}

MyArray.constructor = MyArray;     // link in the constructor
MyArray.prototype = new Array;     // inherit from Array

// Add new method to sum items in the array
MyArray.prototype.sum = function() {
        var theSum = 0;
        for (var i=0 ; i<this.length ; i++)
            theSum += this[i];
        return theSum;
    }

// Add new method to take the average of items in the array
MyArray.prototype.average = function() {
        return this.sum() / this.length;
    }

// Put items in the array. Notice that the new object has access to the push method defined in the parent.
var list = new MyArray();
    list.push(1);
    list.push(2);
    list.push(6);

// Test the new property
list.description = "This is my list";
alert(list.description);

// Test the new methods
alert("sum is " + list.sum());
alert("average is " + list.average());

/* Try this:
1. Replace list.sum() with list.sum in line 32.
2. Add a method to compute the maximum value
3. What happens if the list contains strings?
*/