Snapshot variables for use in functions
I can use this code to sort of "pause" closures in javascript, and get variables that act like more like references than pointers.
by danShumway
JavaScript
//Copyright 2014 Daniel Shumway
//Licensed under MIT
//Code----------------------------------------
//I use long variables here to reduce the likelyhood that they're overwritten during the function call, since I don't know what variable names the user will pass in.
Function.snapshotFunction = function(danShumway_snapshotFunction_func, danShumway_snapshotFunction_keyValues){
//base 2, a value and a key. Probably
for(var danShumway_snapshotFunction_i = 0; danShumway_snapshotFunction_i < danShumway_snapshotFunction_keyValues.length; danShumway_snapshotFunction_i+=2){
//Loop through and create a variable in the local context, passing in the variable from the context we're snapshoting.
eval("var " + danShumway_snapshotFunction_keyValues[danShumway_snapshotFunction_i] + " = danShumway_snapshotFunction_keyValues[danShumway_snapshotFunction_i + 1]");
}
//clone the function, relying on javascript's toString. This is actually surprisingly reliable, or so I'm told.
eval("var toReturn = " + danShumway_snapshotFunction_func);
return toReturn;
}
//Tests-Demonstration-------------------------------
//Make an object.
var testPrimitive = 10;
var testObject = {"currentState":"created state" };
function getPrimitive(){
return testPrimitive;
}
function getObject(){
return testObject;
}
//Returns as expected.
//alert("primitive: " + getPrimitive() + ", object: " + getObject().currentState);
//And if we change the values, we get expected behavior.
//testPrimitive = 15; alert("changed primitive: " + getPrimitive());
//Let's take a snapshot of the variables, so if we swap them later, it won't effect the code.
//this will return a "snapshotted" function. I pass in the function I want to snapshot, and I pass in an array with the values I want to snapshot.
//Pass in as many variables as you want, as long as you follow the [string, value, string, value... ] pattern.
var getPrimitiveSnapshot = Function.snapshotFunction(getPrimitive,...