milkmachine = function(argument){ var r=1, k=2; //..... return r; } milkmachine(); //returns r, good milkmachine.set_return_to_another_variable('k'); milkmachine(); //this should return k 1 Answer
The short answer, as Greg Hewgill commented, is: no (to the best of my knowledge). There are a few shoddy ways you could get that behavior as well as a few recommended ways:
Shoddy Way #1:
One way is to have two versions of the function: one that returns r, the other that returns k. This is not recommended because it is duplicating the same code, just returning something different.
Shoddy Way #2:
Another option would be to add another parameter to the function which would specify the variable you want to be returned:
milkmachine = function(argument, retWhat){ var r; var k; //do something with arguments and variables if (retWhat == "k") return k; else return r; } This is also bad since you're using one function to do multiple things and a function should only do one thing; also, it gives external code more info about the inner workings of the function than is good. (There are probably other, better reasons this is bad, but I can't think of any at the moment.)
Recommended Way #1:
Instead of returning just one value, you could return both values wrapped in a container object:
milkmachine = function(argument){ var r; var k; //do something with arguments and variables return new MilkMachineRetrunValue(r, k); } var retval = milkmachine("some arg"); // access retval.r here // access retval.k here // or you could directly access the variable // that you wanted within the return wrapper // after the call like so: // milkmachine("some arg").k Recommended Way #2
Use an object:
function MilkMachine() { this.r; this.k; } MilkMachine.prototype.run = function(argument) { //do something with arguments and variables } var mm = new MilkMachine(); mm.run("some arg"); // access mm.r here // access mm.k here - 7Recommended Way #1 simplified:
return {'r': r, 'k': k}Izkata– Izkata2013-10-31 20:12:26 +00:00Commented Oct 31, 2013 at 20:12
returnstatement will return a value. You access that value later by storing it into a variable so that you can refer to it later.kinstead of what's the internal variableras it was defined to return?