/    Sign up×
Community /Pin to ProfileBookmark

Arryas having functions

Can Java script arrays contian functions and normal variables as their elements. For example is it possible to have array with var cnt and function initialise() as members.

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@atuchJul 10.2008 — No, you need to create a class if you want to be able to call a function via some sort of object. You can store instantiated classes (objects) in arrays if you want.
Copy linkTweet thisAlerts:
@Jeff_MottJul 10.2008 — Actually you [i]can[/i] store functions in an array element.
var cnt = 0;

function initialize() {
alert(cnt);
}

var theArray = [ cnt, initialize ];
Copy linkTweet thisAlerts:
@JMRKERJul 10.2008 — @JeffMott:

I made an attempt at using your post.


I don't get any errors, but I don't get any 'alerts' either.

Any ideas about how I'm mis-using your code? ?
[code=php]
<html>
<head>
<title>Array Functions</title>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?t=185996

var cnt = 0;
function initialize() { cnt=0; alert(cnt); }
function increment() { cnt++; alert(cnt); }
function review() { alert(cnt); }
var theArray = [ cnt, initialize, increment, review ];
</script>

</head>
<body>
<h1>Array Function Test</h1>
<button onclick="theArray[initialize]">Initialize</button>
<button onclick="theArray[increment]">Increment</button>
<button onclick="theArray[review]">Review</button>
</body>
</html>
[/code]

I also tried putting a single quote around the call also, like

<button onclick="theArray['review']">Review</button>

but no difference.
Copy linkTweet thisAlerts:
@cgishackJul 10.2008 — This is probably too much for what you need, but in case you wanted to redesign your code you can create objects that will handle the functions for you.

here is a sample of how it works
[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<script type="text/javascript">

//***********************************
// CAR OBJECT
//***********************************
function Car()
{
this.make;
this.model;
this.year;
}
Car.prototype.getMake = function()
{
return this.make;
}

//***********************************
// CARS COLLECTION OBJECT
//***********************************
function Cars()
{
this.items = new Array();
}
Cars.prototype.add = function(Car)
{
this.items.push(Car);
}
Cars.prototype.getCar = function(index)
{
return this.items[index];
}


//***********************************
// DEMO
//***********************************
var myCar = new Car();
myCar.make = "Chevy";
myCar.model = "Nova";
myCar.year = "1977";

var CarCollection = new Cars();
CarCollection.add(myCar);

//get Car Make
alert(CarCollection.getCar(0).getMake());


</script>

</body>
</html>

[/code]
Copy linkTweet thisAlerts:
@Jeff_MottJul 10.2008 — Once you have a function in an array &#8212; [font=courier]var someArray = [ initialize ][/font] &#8212; then you'd call it like this: [font=courier]someArray[0]()[/font]. But now that I see the way you're trying to use it, you don't really want a regular array, you want an associative array.var theArray = {};
theArray["review"] = review; // store the function
theArray["review"](); // call the function


Edit: I'd just like to add that although this may solve your immediate problem, creating a class&#8212;as atuch suggested and cgishack demonstrated&#8212;is the more elegant solution, and you should give it a try if you have the time.
Copy linkTweet thisAlerts:
@KorJul 10.2008 — 
Edit: I'd just like to add that although this may solve your immediate problem, creating a [COLOR="Blue"]class[/COLOR]&#8212;as atuch suggested and cgishack demonstrated&#8212;is the more elegant solution, and you should give it a try if you have the time.[/QUOTE]

It is not a real [I]class[/I], as javascript it is not a class-oriented language, it is a prototype-oriented one. Javascript works only with objects and instances, and they are constructed via cloning (prototype) or simply "from nothing". Javascript has no classes, nor classes' constructors, nor classes' constructors' arguments
Copy linkTweet thisAlerts:
@Declan1991Jul 10.2008 — And closures in JavaScript can often be more suitable.<i>
</i>function somefunction(a) {
var t = a;
return {
"get":function(){
return t;
},
"set":function(a){
t = a;
}
};
}
var whatever = somefunction("a");
alert(whatever.get());
whatever.set(10);
alert(whatever.get());
It's a trivial example, but you get the idea.
Copy linkTweet thisAlerts:
@Jeff_MottJul 10.2008 — It is not a real [I]class[/I], as javascript it is not a class-oriented language, it is a prototype-oriented one. Javascript works only with objects and instances, and they are constructed via cloning (prototype) or simply "from nothing". Javascript has no classes, nor classes' constructors, nor classes' constructors' arguments[/QUOTE]
I call it a class because for the most part we treat it like one, and it's easier, especially for people newer to JavaScript, to refer to it that way since it's a concept they usually already understand.
Copy linkTweet thisAlerts:
@seatoskyhkJul 10.2008 — Or you can do that:

<i>
</i>var yourArray = [
{
init: function(){ alert('yooo'); },
others: function() {}
},
{
isok:true,
init: function() {alert(yourArray[1].isok); },
whatever: function () {}
},
{}
];


// accessing it:
yourArray[0].init();
yourArray[1].init();
yourArray[1].whatever();
Copy linkTweet thisAlerts:
@Declan1991Jul 10.2008 — Yes, and remember the length of that array will be 3 because of the empty object. What exactly are you trying to do, or is it a learning exercise.
×

Success!

Help @aniketto spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.3,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...