JS:用方法捕获对象在某个时间点的静态快照
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
this
是对对象的引用。您没有存储对象的副本。您正在存储对该对象的引用。如果您想要副本,则需要手动复制属性。最简单的方法是使用$.extend()
: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()
:好吧,术语是“深度”复制。我本以为是相反的(只是得到一个印象而不是物体本身)。所以无论如何,Cletus 是对的,但语法是:
显然“快照”在开发人员行话中是“克隆”。
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:
And apparently 'snapshot' is 'clone' in developer lingo.