How to preserve the state of JavaScript closure?
I am working on a migration platform to migrate web applications from a device to another. I am extending it to add the support for preserving JavaScript state. My main task is to create a file representing the current state of the executing application, to transmit it to another device and to reload the state in the destination device.
The basic solution I adopted is to navigate the window object and to save all its descendant properties using JSON as base format for exportation and extending it to implement some features:
- preserving object reference, even if cyclic (dojox.开发者_运维知识库json.ref library)
- support for timers
- Date
- non-numericproperties of arrays
- reference to DOM elements
The most important task I need to solve now is exportation of closures. At this moment I didn't know how to implement this feature.
I read about the internal EcmaScript property [[scope]]
containing the scope chain of a function, a list-like object composed by all the nested activation context of the function. Unfortunately it is not accessible by JavaScript.
Anyone know if there is a way to directly access the [[scope]]
property? Or another way to preserve the state of a closure?
This sounds like an impossible feat as you would need access to the references stored in each variable.
The best solution would probably be to first refactor your code into storing state on an available object - that way you could easily use JSON.stringify/parse to save/restore it.
So go from
var myFuncWithScope = (function() {
var variable = 0;
return function() {
return variable++;
}
})();
var serializedState = .... // no can do
to
var state = {
myScope = {
variable: 0
}
};
var myFuncWithoutScope = function(){
return state.myScope.variable++;
}
var serializedState = JSON.stringify(state);
From where are you executing? If you are a native app or web browser extension you may have some hope, via internal access to whichever scripting engine it's using. But from a script in web content, there is no hope.
[[Scope]]
is one ECMAScript internal property that you cannot access or preserve from inside the interpreter, but far from the only one; almost all of the [[...]]
properties are not accessible. Function code references, prototypes, properties, enumerability, owner context, listeners, everything to do with host objects (such as DOM nodes)... there are infinitely many ways to fail.
You can't preserve or migrate web applications without requiring them to follow some strict rules to avoid all but the most basic JS features.
精彩评论