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
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?
*/
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.