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?
Method 3: unshift() method The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method.
You Cant. However you can create a functional interface and then use lambdas to populate the array. Then you can create a reference to the interface and assign it to a random implementation from the array.
Adding a method to the object Adding a method to a javascript object is easier than adding a method to an object constructor. We need to assign the method to the existing property to ensure task completion.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With