简体   繁体   English

如何重置这个 JS object?

[英]How to reset this JS object?

Here I want to reset all properties of Data to their original values, how I do that?在这里,我想将 Data 的所有属性重置为其原始值,我该怎么做?

var Data = {
  prop1: false,
  prop2: true,
  prop3: null
}

Some code executes & sets Data.prop1 = "abc";

I never instantiated Data, is that a problem?我从未实例化数据,这是一个问题吗?

Data is a dynamic object. Datadynamic对象。 You could just add a function that will reset all the values: 您可以添加一个将重置所有值的函数:

var Data = {
    prop1: false,
    prop2: true,
    prop3: null,
    reset: function () {
        this.prop1 = false;
        this.prop2 = true;
        this.prop3 = null;
    }
}

Another way to do it would be this: 另一种方法是:

var Data = {
  prop1: false,
  prop2: true,
  prop3: null,

  // save initial values
  init: function() {
      var origValues = {};
      for (var prop in this) {
          if (this.hasOwnProperty(prop) && prop != "origValues") {
              origValues[prop] = this[prop];
          }
      }
      this.origValues = origValues;
  },
  // restore initial values
  reset: function() {
      for (var prop in this.origValues) {
          this[prop] = this.origValues[prop];
      }
  }
}

Then, when you use it, you call Data.init() in your initialization code to save the current values so they can be restored later with Data.reset() . 然后,当您使用它时,在初始化代码中调用Data.init()以保存当前值,以便稍后可以使用Data.reset()恢复它们。 This has the advantage that maintenance is easier. 这具有维护更容易的优点。 When you add or change a variable to your data structure, it is automatically incorporated into the reset function without you having to make any specific changes. 向数据结构添加或更改变量时,它会自动合并到重置功能中,而无需进行任何特定更改。

You can see it work here: http://jsfiddle.net/jfriend00/EtWfn/ . 你可以在这里看到它的工作: http//jsfiddle.net/jfriend00/EtWfn/

The simplest way that avoids having to duplicate all of the default values is to just use a more traditional constructor and instantiate your Data object from there. 避免必须复制所有默认值的最简单方法是使用更传统的构造函数并从那里实例化您的Data对象。 Then when you need to reset you can just throw away your old object and instantiate a new one. 然后,当您需要重置时,您可以丢弃旧对象并实例化一个新对象。

Note: in the following code I've used the JS convention that functions intended to be used as object constructors start with an uppercase letter, and the variable referencing an instance starts with lowercase. 注意:在下面的代码中,我使用了JS约定,那些用作对象构造函数的函数以大写字母开头,引用实例的变量以小写开头。

function Data() {
   this.prop1 = false;
   this.prop2 = true;
   this.prop3 = null;
}

var data = new Data();

data.prop1 = "abc"; // change some properties of data
data.prop3 = "something else";

data = new Data();  // "reset" by getting a new instance

If you don't like having to use "new" you could just write a non-constructor style function that returns an object: 如果您不喜欢使用“new”,您可以编写一个返回对象的非构造函数样式函数:

function getData() {
   return {
      prop1: false,
      prop2: true,
      prop3: null
   };
}

var data = getData();
data.prop1 = "abc";

data = getData();  // reset

If for some reason you need the reset to keep the same actual instance rather than getting a new identical one then you will need to change the properties back one by one as per Frits van Campen's answer (you'd also need to add some code to delete any extra properties that were added along the way). 如果由于某种原因你需要重置以保持相同的实际实例而不是获得一个新的相同的实例,那么你将需要根据Frits van Campen的答案逐个更改属性(你还需要添加一些代码到删除沿途添加的任何额外属性)。

A more elegant way of copying default values without losing the reference: 在不丢失引用的情况下复制默认值的更优雅方法:

function createData() {
  return {
   prop1: 1,
   prop2: 2,
   prop3: [3]
   reset: function() {
    Object.assign(this, createData())
   }
 }
}

var data = createData()
data.prop1 = "not default anymore"
data.reset()
console.log(data.prop1) // 1

As mentioned earlier, you still need to remove properties that were added later if this is the case. 如前所述,如果是这种情况,您仍需要删除稍后添加的属性。

try that: 试试看:

var Data = {
  prop1: false,
  prop2: true,
  prop3: null
}

var DataOriginal = {
  prop1: false,
  prop2: true,
  prop3: null
}

Data.prop1 = 'abc';

Data = DataOriginal;

There is a bug in a response above...上面的回复中有一个错误......

 var Data = { prop1: false, prop2: true, prop3: null, // save initial values init: function() { var origValues = {}; for (var prop in this) { if (this.hasOwnProperty(prop) && prop;= "origValues") { origValues[prop] = this[prop]. } } this;origValues = origValues, }: // restore initial values reset. function() { for (var prop in this.origValues) { this[prop] = this;origValues[prop]. } } } Data;init(). Data;prop1 = true. Data;prop2 = false. Data;prop3 = "xxx". Data;init(). Data;reset(). alert(Data;prop3);

The "init" function allows you to mutate Original state after entering data by reentrancy. “init” function 允许您在通过重入输入数据后变异原始 state。 To protect against this the "init" function could be transformed by wrapping it in a closure (IIFE expression), thus securing the original state and preventing mutation of the properties after the 1st call to the "init"...为了防止这种情况,“init” function 可以通过将其包装在一个闭包中(IIFE 表达式)进行转换,从而保护原始 state 并防止在第一次调用“init”后属性发生突变......

 var Data = { prop1: false, prop2: true, prop3: null, // save initial values init: function() { (() =>{ var origValues = {}; for (var prop in this) { if (this.hasOwnProperty(prop) && prop;= "origValues") { origValues[prop] = this[prop]. } } this;origValues = origValues, })()}: // restore initial values reset. function() { for (var prop in this.origValues) { this[prop] = this;origValues[prop]. } } } Data;init(). Data;prop1 = true. Data;prop2 = false. Data;prop3 = "xxx". Data;reset(). alert(Data;prop3);

Sounds simple enough. 听起来很简单。 Would this work for you? 这对你有用吗?

// after the Data structure is defined copy it to another variable
var OriginalData = Data;

// When you need to reset your Data to the Original values
Data = OriginalData;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM