当还传入其他对象时,为什么 Object.assign({}, ...) 使用空对象文字?

2023-11-29

我正在阅读 Redux 减速器的介绍(https://redux.js.org/introduction/ Three-principles)其中包含以下减速器示例:

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case 'COMPLETE_TODO':
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: true
          })
        }
        return todo
      })
    default:
      return state
  }
}

从它的文档看来(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) that Object.assign()会将传入其中的所有对象“合并在一起”。然而,在这种情况下,todo and {completed: true}已经是对象了,所以我看不出传递空对象文字的意义,{},作为第一个参数Object.assign()。有人可以澄清这一点吗?


当你使用Object.assign,您给它的第一个对象会将所有其余对象合并到其中。也就是说,第一个对象将会发生变异。

如果您想避免改变要合并的对象,则将空对象作为第一个参数传递以防止任何组件对象发生更改会很有帮助。

这是一个展示差异的示例:

const obj1 = {
  foo: "bar"
}

const obj2 = {
  key: "value"
}

// Here, obj1 is the same after the Object.assign call
console.log(Object.assign({}, obj1, obj2));
console.log(obj1)
console.log(obj2)

console.log("\n\n")

// Note that after this call, obj1 holds both keys. So this will mutate it:
console.log(Object.assign(obj1, obj2));
console.log(obj1) // This is different now
console.log(obj2)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当还传入其他对象时,为什么 Object.assign({}, ...) 使用空对象文字? 的相关文章

随机推荐