views:

44

answers:

2

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

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

+2  A: 

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);
cletus
On paper that looks right but in practice the use case functionality is the same – only now I have infinite recursion (dom.m == dom.m.old == dom.m.old.old etc)…The $.extend() assignment there is the same as doing:for(i in this) this.old[i] = this[i];I can eliminate recursion by going:for(i in this) if(typeof this[i] !== 'function' …taking on board what you're saying about *this*, I thought I could assign eval(this[i]) (which I thought would return the unbound contents as they stand), but surprisingly this doesn't help at all.
Barney
A: 

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.

Barney