Is it possible to add a method to an array() in javascript? (I know about prototypes, but I don\'t want to add a method to every array, just one in particular).
The
Arrays are objects, and can therefore hold properties such as methods:
var arr = [];
arr.methodName = function() { alert("Array method."); }
Yep, easy to do:
array = [];
array.foo = function(){console.log("in foo")}
array.foo(); //logs in foo
Just instantiate the array, create a new property, and assign a new anonymous function to the property.
var someArray = [];
var someArray.someMethod = function(){
alert("Hello World!");
}
someArray.someMethod(); // should alert
var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);
function drawChart(){
{
//...
var importantVars = [list of important variables];
importantVars.redraw = function(){
//Put code from updateChart function here using "this"
//in place of importantVars
}
return importantVars;
}
Doing it like this makes it so you can access the method directly after you receive it.
i.e.
var chart = drawChart();
chart.redraw();