DEV Community

florent giraud
florent giraud

Posted on

[REMINDER-6] Object.assign/setPrototypeOf

ASSIGN

this method copies all the enumerable own properties of one or more objects into another

It mean's values are cloned, and objects references are copied live for vuejs < 3 (I didn't check for vue 3 reactivity but it's different normally).

example:

const original = {
  name: 'Fiesta',
  car: {
    color: 'blue'
  }
}

const copied = Object.assign({}, original)

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow
Enter fullscreen mode Exit fullscreen mode

Name doesn't change everywhere because it's not an object. For car yes and no matter if you change the copied object or the orignal one.

IMPORTANT: Spread operator does the same because it uses Object.assign behind the scene

const original = {
  name: 'Fiesta',
  car: {
    color: 'blue'
  }
}

const copied = {...original}

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow
Enter fullscreen mode Exit fullscreen mode

setPrototypeOf

Copy all proto values from an object to another one.


const animal = {
  isAnimal: true
}
const mammal = {
  isMammal: true
}

// mammal.__proto__ = animal
Object.setPrototypeOf(animal, mammal). // Same as doing before
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!