javascript 如何重置这个JS对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8440357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:27:31  来源:igfitidea点击:

How to reset this JS object?

javascript

提问by Baconbeastnz

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?

我从来没有实例化数据,这是一个问题吗?

回答by Halcyon

Datais a dynamicobject. You could just add a function that will reset all the values:

Data是一个dynamic对象。您可以添加一个函数来重置所有值:

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

回答by jfriend00

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(). 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.

然后,当您使用它时,您调用Data.init()初始化代码来保存当前值,以便以后可以使用Data.reset(). 这具有维护更容易的优点。当您向数据结构添加或更改变量时,它会自动合并到重置功能中,而无需进行任何特定更改。

You can see it work here: http://jsfiddle.net/jfriend00/EtWfn/.

你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/EtWfn/

回答by nnnnnn

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. Then when you need to reset you can just throw away your old object and instantiate a new one.

避免必须复制所有默认值的最简单方法是使用更传统的构造函数并从那里实例化您的 Data 对象。然后当您需要重置时,您可以扔掉旧对象并实例化一个新对象。

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 的回答将属性一一改回(您还需要添加一些代码到删除沿途添加的任何额外属性)。

回答by Pietro Coelho

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.

如前所述,如果是这种情况,您仍然需要删除稍后添加的属性。

回答by David Laberge

try that:

试试看:

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

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

Data.prop1 = 'abc';

Data = DataOriginal;

回答by Dean Marshall

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;