简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM