JS:用方法捕获对象在某个时间点的静态快照

发布于 2024-08-28 11:53:58 字数 775 浏览 3 评论 0原文

我有一个 JS 对象,用于存储 DOM 信息,以便在复杂的 GUI 中轻松引用。

它是这样开始的:

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

我在窗口调整大小时调用该函数:

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

问题出在 dom.m.old 上。我本以为,在分配其他属性的新值之前,在 dom.m.update() 方法中调用它,在任何时间点 dom.m.old 都会包含一个快照截至上次更新的 dom.m 对象 - 但相反,它始终与 dom.m 相同。我刚刚得到了一个毫无意义的递归方法。

为什么这不起作用?如何获得在没有明确告知的情况下不会更新的对象的静态快照?

非常欢迎解释我什至不应该一开始就远程做任何事情的评论:)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟织青萝梦 2024-09-04 11:53:58

this 是对对象的引用。您没有存储对象的副本。您正在存储对该对象的引用。如果您想要副本,则需要手动复制属性。最简单的方法是使用 $.extend()

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

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);
明天过后 2024-09-04 11:53:58

好吧,术语是“深度”复制。我本以为是相反的(只是得到一个印象而不是物体本身)。所以无论如何,Cletus 是对的,但语法是:

this.old = $.extend(true,{},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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文