17

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 reason I want to do this is because I have the following code

function drawChart()
{
    //...
    return [list of important vars]
}

function updateChart(importantVars)
{
    //...
}

var importantVars = drawChart();

updateChart(importantVars);

And I want to be able to do something like this instead:

var chart = drawChart();<br>
chart.redraw();

I was hoping there was a way I could just attach a method to what i'm returning in drawChart(). Any way to do that?

user1167650
  • 3,177
  • 11
  • 34
  • 46
  • This has already be answered multiple times, however, keep this in mind: *methods in JavaScript are first-class [function] values*. That is, they are *just functions* that are named by -- that is, are the result of evaluating -- *properties*. –  Jul 10 '12 at 21:15
  • 1
    This is clearly possible, but is it advisable? Are there side effects? When iterating over the array, will the method get in the way? Does the method count when getting the Array's length? – Jesse Hattabaugh Jul 23 '14 at 22:58

5 Answers5

39

Arrays are objects, and can therefore hold properties such as methods:

var arr = [];
arr.methodName = function() { alert("Array method."); }
jeff
  • 8,300
  • 2
  • 31
  • 43
8

Yep, easy to do:

array = [];
array.foo = function(){console.log("in foo")}
array.foo();  //logs in foo
jjathman
  • 12,536
  • 8
  • 29
  • 33
5

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
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
4
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();
Aust
  • 11,552
  • 13
  • 44
  • 74
  • Frustrating that this answer didn't get more upvotes. This is the only one that addresses the OP: how to actually embed array with the associated function **in the return result**. (As it happens, this is exactly what I needed to know. Thanks, @Aust !) – Mike Williamson Dec 07 '17 at 01:41
  • Can you access and mutate the array's values from inside that function? – Andrew S Aug 06 '21 at 22:24
0
var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);
Sandeep Sherpur
  • 2,418
  • 25
  • 27
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 03 '17 at 12:08