Reputation: 67
I am writing a javascript program and I want to be able to store function calls that create 3D objects inside of an array. I want to be able to put
draw_cylinder(0,0,3,2);
draw_sphere(0,0,5,3);
draw_cone(17,0,7,3);
draw_cube(-1,-1,2, 1,1,3);
into array shapes[]
and then eventually run the program and have each function be called from the array.
Upvotes: 0
Views: 995
Reputation: 674
Do you want to have the functions available in the array or function calls with those specific values?
Just to have the calls, you can do:
var a = [];
a.push(draw_cylinder);
a.push(draw_sphere);
a.push(draw_cone);
a.push(draw_cube);
a[2](17,0,7,3);
If you want the latter, you'd want to use bind
to curry the function:
var a = [];
a.push(draw_cylinder.bind(null, 0, 0, 3, 2));
a[0](); // will do whatever draw_cylinder(0,0,3,2) does
Currying functions - http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html
Bind documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Upvotes: 1
Reputation: 1336
My first thought would be:
var a = [];
a.push(function(){ draw_cylinder(0, 0, 3, 2); });
a.push(function(){ draw_sphere(0, 0, 5, 3); });
a.push(function(){ draw_cone(17, 0, 7, 3); });
a.push(function(){ draw_cube(-1, -1, 2, 1, 1, 3); });
for(var i = 0; i < a.length; i++){
a[i]();
}
Upvotes: 1