I am trying to put a variable name within a variable passed to a function, and perform an operation on it.
Here is my code (simplified):
function animloop(object, increment, max, direction) {
if (direction == 1) {
object += increment;
if (object >= max) {
clearInterval( pingpong.animloop );
}
}
if (direction == -1) {
object -= increment;
if (object <= max) {
clearInterval( pingpong.animloop );
}
}
}
If I first set the variable xyz = 10; and then call pingpong.animloop = setInterval( animloop( xyz, 0.1, 40, 1 ) ), 1000 / 60 );, it won’t work.
What I learned is that when I call object += increment;, it isn’t actually modifying the value of whatever object is. Basically the value of xyz isn’t changing.
Hopefully you understand what I’m trying to do. :/
Primitive data types are passed by-value in JS, which means you’re not accessing the
xyzyou defined outside of the function call. You’re accessing some OTHER variable that has been given a copy of the valuexyzhad at the time of the function call.There’s a few ways around it.
global vars:
return value:
or use an object. Objects are passed by reference, so this would work: