开发者

JS: capture a static snapshot of an object at a point in time with a method

开发者 https://www.devze.com 2022-12-26 10:11 出处:网络
I have a JS object I use to store DOM info for easy reference in an elaborate GUI. 开发者_如何学CIt starts like this:

I have a JS object I use to store DOM info for easy reference in an elaborate GUI.

开发者_如何学C

It starts like this:

var dom = {
    m:{
        old:{},

        page:{x:0,y:0},
        view:{x:0,y:0},

        update:function(){
            this.old = this;
            this.page.x = $(window).width();
            this.page.y = $(window).height();
            this.view.x = $(document).width();
            this.view.y = window.innerHeight || $(window).height();
        }

I call the function on window resize:

$(window).resize(function(){dom.m.update()});

The problem is with dom.m.old. I would have thought that by calling it in the dom.m.update() method before the new values for the other properties are assigned, at any point in time dom.m.old would contain a snapshot of the dom.m object as of the last update – but instead, it's always identical to dom.m. I've just got a pointless recursion method.

Why isn't this working? How can I get a static snapshot of the object that won't update without being specifically told to?

Comments explaining how I shouldn't even want to be doing anything remotely like this in the first place are very welcome :)


this is a reference to an object. You're not storing a copy of an object. You're storing a reference to that object. If you want a copy you'll need to copy the properties by hand. The easy way is to use $.extend():

this.old = $.extend({}, this);


OK right, the terminology is 'deep' copy. I would've thought it was the other way round (just get an impression rather than the object itself). So anyway Cletus is right but the syntax is:

this.old = $.extend(true,{},this)

And apparently 'snapshot' is 'clone' in developer lingo.

0

精彩评论

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