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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs