user1167650
user1167650

Reputation: 3207

Add a method to Array object in Javascript?

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?

Upvotes: 17

Views: 45705

Answers (5)

Sandeep Sherpur
Sandeep Sherpur

Reputation: 2802

var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);

Upvotes: 0

Aust
Aust

Reputation: 11602

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();

Upvotes: 4

jeff
jeff

Reputation: 8348

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

var arr = [];
arr.methodName = function() { alert("Array method."); }

Upvotes: 40

Justin Niessner
Justin Niessner

Reputation: 245419

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

Upvotes: 6

jjathman
jjathman

Reputation: 12604

Yep, easy to do:

array = [];
array.foo = function(){console.log("in foo")}
array.foo();  //logs in foo

Upvotes: 8

Related Questions