What is the difference between {something: value} & Object.assign ({}, {something: value})

I study reaction and contraction. I wanted to find the difference between the two codes.

export default function xReducer (state = [], action) {
    switch (action.type) {
        // I am simply assigning my key value to the action property
        case 'SOMETHING': {
             return [ ...state, { myKey: action.x } ]
        }
        // I am using Object.assign
        case 'SOMEMORE': {
             return [ ...state, Object.assign({}, { myKey: action.x }) ]
        }
    }
}
+4
source share
2 answers

Using Object.assignin your example does not do any good. Object.assigncreates a shallow copy. Basically, use Object.assignwill create a new instance of the object, preserving the original object. In terminology, Reactall this concerns the preservation of an immutable object.

var obj1 = {prop1: "A"};
var obj2 = Object.assign({}, obj1);
obj1 === obj2; //false as they are 2 different instances

This can be achieved:

var obj2 = {
  prop1: obj1.prop1
};
obj1 === obj2; //false as they are 2 different instances

, Object.assign (string, number, boolean ), ( ). Object.assign , Array, Function, Object, null, undefined.

:

var obj3 = {
  fn: function() {}
};

var obj4 = Object.assign({}, obj3);
obj3.fn === obj4.fn; //true as Object.assign will not create a new instance of fn

Object.assign .

. Mozilla: https://developer.mozilla.org/en-US/docs/Glossary/Primitive

+1

, . Object.assign , , . :

let options = Object.assign({}, defaultOptions, passedOptions)

, , , , , .

+3

Source: https://habr.com/ru/post/1670242/


All Articles