存储JavaScript对象的状态 [英] Store state of a JavaScript Object

查看:97
本文介绍了存储JavaScript对象的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的javscript对象中存储'this'的统计信息,以便稍后在我的应用程序中我可以将'this'返回到先前的状态。我以为我可以用封闭来完成,但到目前为止我还没有成功。我的想法是做这样的事情

Im trying to store the stats of 'this' in my javscript object so that later on in my application I can return 'this' to a previous state. I thought I could accomplish using a closure but so far I haven't successful. My idea was to do something like this

function SavedFeature() {
    var self = this;

    this.savedItem;

    this.storeState = function() {
        this.savedItem = storeClosure();
    }

    function storeClosure() {
        var closure = self;
        return function() {
            return closure;
        };
    };

    //other things the user can change...
}

所以稍后在我的应用程序中,如果我需要回到我调用storeState的时候我可以做到

so later on in my application if I needed to return to the point when I called storeState I could just do

//return the object I put in my closure
var backToNormal = savedFeature.savedItem();

虽然因为我调用storeState()后对savedFeature对象的任何更改都不起作用反映在项目中我从被调用的savedItem()中检索。我猜这种情况正在发生,因为闭包被设置为self的引用而不是复制到新实例。

that doesn't work though because any changes to my savedFeature object after I call storeState() are being reflected in the item im retrieving from called savedItem(). I'm guessing this is happening because closure is being set to a reference of self instead of copied to a new instance.

无论如何都要将我的整个对象的状态存储在这样的闭包中,或者我是否需要以其他方式存储它。

Is there anyway to store the state of my entire object in a closure like this or do I need to store this some other way.

推荐答案

您遇到的问题是js对象是通过引用传递的。这意味着对您的对象执行的所有更改都将应用于您的 obj.savedItem 属性。

The issue you are running into is that in js objects are passed by reference. This means that all changes performed on your object will apply to your obj.savedItem property.

修复:将深度克隆存储到 obj.savedItem

Fix: Store a deep clone into obj.savedItem

 this.storeState = function() {
     this.savedItem = _.cloneDeep(this); // or _.clone(this, true);
 }

cloneDeep 是一个 lodash 方法,大多数js libs提供自己的一个,例如jQuery的 $ .extend 等。

cloneDeep is a lodash method, most js libs supply one of their own, e.g. jQuery's $.extend, etc.

您可以轻松推出自己的深度克隆功能,查找此选项主题

You could easily roll your own deep clone function, look up the options on this thread.

jQuery的完整示例:

function SavedFeature() {
    this.savedItem;

    this.clone = function() {
       return $.extend(true, {}, this);
    },

    this.storeState = function() {
        this.savedItem = this.clone();
    }
}

这样做可以让你适应不同的环境更改 clone 方法,因为它正在使用已使用的库方法。

Doing it this way allows you adapt to different environments by changing your clone method as it is facading the used library method.

这篇关于存储JavaScript对象的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆