loading...

[REMINDER-6] Object.assign/setPrototypeOf

f3ltron profile image florent giraud ・1 min read

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

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

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

Posted on by:

Discussion

pic
Editor guide