I want to save the state of window, without having changes made later affect the saved state

200 Views Asked by At

I just started a project that I'm calling Diff.js. It has several functions, for detecting differences. One of the functions is detectNew(original_state, current_state);

It detects properties in the current_state, that are not in the original_state. What I want to do is detect new properties in the window object, but what I'm doing is:

var _window = window;
// ~Script that changes window~
detectNew(_window, window);

But the _window variable changes along with window. Anyone know how to prevent this behavior?

3

There are 3 best solutions below

0
On BEST ANSWER
// Create a backup variable.
var _window = {};

// Put all the properties in it.
for (prop in window) 
    _window[prop] = window[prop];

I ended up using this little snippet.

1
On

You need to copy the window state.

You could use jQuery like:

var _window = {};
jQuery.extend( true, _window, window );

// change window

detectNew( _window, window )

Just a suggestion...I haven't tried this.

1
On

window has a lot of stuff in it!

You need to do a deep copy of your object instead of just assignment, because assignment is by reference. But copying window isn't easy. I wanted to be clever and use the built-in JSON support of modern browsers:

var _window = JSON.parse(JSON.stringify(window));

But that doesn't work due to circular references. I'd recommend you limit the scope of interest to some sub-object of window. Window just has too many built-in things and it's probably always changing.