开发者

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

开发者 https://www.devze.com 2023-02-09 17:01 出处:网络
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);

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);

开发者_C百科But the _window variable changes along with window. Anyone know how to prevent this behavior?


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.


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.


// 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消