简体   繁体   English

创建一个返回具有不可变状态的对象的工厂函数

[英]Create a factory function that returns an object with immutable state

Link to CodePen https://codepen.io/jaspercreel/pen/Mvaodp链接到 CodePen https://codepen.io/jaspercreel/pen/Mvaodp

Basically, my function will look something like this:基本上,我的函数看起来像这样:

const Factory = (args) => {

  const state = {
    args
  }

  const methods = {  

    getState() => {
      return args;
    },

    setState(args) => {
      state.args = args;
    },

    doStuffWithState() => {
      let args = this.getState();
      function(args) {
        return args plus something else;
      }();
    }

  }

  return Object.assign({}, methods);

}

The problem is that whenever I call doStuffWithState() it changes the state object.问题是,每当我调用 doStuffWithState() 时,它都会更改状态对象。 I thought I would be safe creating a new variable with the returned state, but I learned that when referencing an object you are only creating a new reference.我以为用返回的状态创建一个新变量是安全的,但我了解到,在引用一个对象时,你只是在创建一个新的引用。 So my question is this, how can I create immutable state that can be referenced but not changed (except by helper functions) in a factory function?所以我的问题是,如何在工厂函数中创建可以引用但不能更改(辅助函数除外)的不可变状态?

My end goal is to create a sorter factory function that will create an object that takes arrays and sorts and searches them in different ways.我的最终目标是创建一个排序器工厂函数,该函数将创建一个接受数组并以不同方式排序和搜索它们的对象。 I want to be able to store a default array in the sorter that can be referenced to return different sorting options but not changed.我希望能够在排序器中存储一个默认数组,该数组可以被引用以返回不同的排序选项但不会更改。 Any advice?有什么建议吗?

One approach would be to store the JavaScript object as a JSON string with JSON.stringify() and use JSON.parse() to parse the JSON string to a JavaScript object, which does not reference the original object passed that is stored as a string.一种方法是使用JSON.stringify()将 JavaScript 对象存储为JSON字符串,并使用JSON.parse()JSON字符串解析为 JavaScript 对象,该对象不引用存储为字符串的原始对象.

You can also utilize Promise to return a JavaScript object reflecting properties of JSON string, passed to Object.assign() , which can return modified properties or values of original object, without affecting original object passed to Factory , which returns a Promise value as the JSON string format of the original passed object.您还可以利用Promise返回一个反映JSON字符串属性的 JavaScript 对象,传递给Object.assign() ,它可以返回修改后的属性或原始对象的值,而不影响传递给Factory的原始对象,它返回一个Promise值作为原始传递对象的JSON字符串格式。

 // `const` declaration cannot be changed or deleted const Factory = (args) => Promise.resolve(JSON.stringify(args)); const state = Factory({ abc: [1, 2, 3] }); state.then(data => console.log(data)); // `{"abc":[1,2,3]}` // change object passed to `Factory` state.then(data => Object.assign(JSON.parse(data), { abc: JSON.parse(data).abc.concat(4, 5, 6) })) // do stuff with modified `JSON` `args` as JavaScript object.then(res => {console.log(res); return res}) // `{"abc":[1,2,3,4,5,6]}`.then(res => // `res`: `{"abc":[1,2,3,4,5,6]}` // `state` `Promise` value is original object // as valid `JSON` `{"abc":[1,2,3]}` // return original `args` as `JSON` string state.then(data => {console.log(res, data); return data}) ) // original `args` as JavaScript object.then(o => console.log(JSON.parse(o)))

I appreciate all the answers and comments guys.我感谢所有的答案和评论。 It turns out I was being very dumb.事实证明我很愚蠢。 So in my tests I was sometimes able to return a value without altering the original and sometimes not, and I could not figure out why.所以在我的测试中,有时我能够在不改变原始值的情况下返回一个值,有时则不能,我无法弄清楚为什么。 Now I know it is because in my tests that altered the state, I was calling sort() on an array, and sort is an in-place function.现在我知道这是因为在我改变状态的测试中,我在数组上调用 sort(),而 sort 是一个就地函数。 It alters the original array.它改变了原始数组。

Such a small oversight on my part, but I consider it a learning experience.我的疏忽如此之小,但我认为这是一种学习经验。 Thanks again for the effort in the help guys.再次感谢帮助人员的努力。 Hopefully my dumb mistake can be a learning experience for others too.希望我的愚蠢错误也能成为其他人的学习经验。

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

相关问题 JavaScript:创建使用具有特定属性的方法返回对象的工厂函数 - JavaScript: Create Factory Function that Returns Object with Methods That Have Specific Properties 试图修改一个功能'pick'函数,以便它返回一个修改对象的选择,以便将redux不可变映射状态转换为props - Trying to modify a functional 'pick' function so that it returns a pick on a modified object for redux immutable map state to props 如何从 JavaScript 中的工厂 function 返回一个不可变的 object - How to return an Immutable object from a factory function in JavaScript 在 javascript 中创建不可变的 object - Create immutable object in javascript 是 javascript function object 不可变的实例 - is an instance of a javascript function object immutable 存储状态下的每个对象都应该是不可变的吗? - Should every object in the store state be immutable? 具有不可变状态的循环内的对象更新 - Object updation inside loop with immutable state 改变对象值的不变函数 - immutable function that alter object value 不可变变量和纯 function 更新 state - Immutable variable and pure function updating state 如何在工厂函数中创建和返回私有对象? - How to create and return a private object within a factory function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM