Reputation: 800
I have a constructor that I created which has a method which modifies a bunch of local variables. My problem is that the method may throw some error, so when an error occurs I want to restore the scope to it's previous state. Obviously I could create a bunch of temporary variables and then just assign those to the variables that the constructor actually uses, but that's not really an optimal solution. I want to know if there is any way I can modify the variables from the method and restore them to the state they were before the method was called in the case of an error.
Upvotes: 0
Views: 50
Reputation: 1802
use stack,
eg.
var Stack = new Array();
doModification(10,'');
function doModification(A,B){
Stack.push(A);
Stack.push(B);
// after modifying,
try{
A= 10;
if(B == 0) throw new Error("Divide by Zero Exception.");
B= A/B;
}
catch(e){
// if exception then restore original vars
B = Stack.pop();
A = Stack.pop();
alert(e.description);
}
// else if error doesn't come then, clear the stack
Stack = [];
}
Upvotes: 2
Reputation: 86270
Other than the global scope, there's no real way to interact with scopes in JavaScript. You can create objects, that act as scopes, though.
function Scope(data){
this.data = data;
this.stages = [];
this.save(data);
}
Scope.prototype.save = function(){
var oldData = JSON.parse(JSON.stringify(this.data));
this.stages.push(oldData);
}
Scope.prototype.undo = function(){
var lastData = this.stages.pop();
this.data = lastData;
}
We can then create a scope with some data.
var scope = new Scope({name: "John"});
Now, we have a strange function with highly preferental treatment for people named Paul.
function myFunction(data) {
if (data.name === "John") {
data.name = "Paul";
throw new Error("I don't like John!");
}
}
We can then call our function in a try/catch.
try {
myFunction(scope.data);
}
catch (e) {
// scope.data is {name: "Paul"}
scope.undo();
// scope.data is {name: "John"}
}
Upvotes: 3