Phil Mok
Phil Mok

Reputation: 4050

What is the difference between Object.assign and Object.setPrototypeOf in JavaScript?

Let's say I have an animal object with a speak function:

function speak() {
  console.log(this.sound)
}

let animal = {
  speak
}

And I have a dog with a sound:

let dog = {
  sound: "Woof!"
}

If I want dog to inherit speak from animal I can use Object.assign or Object.setPrototypeOf. They seem to produce the same results:

let luke = Object.assign(dog, animal)

luke.speak() // Woof!

let bruno = Object.setPrototypeOf(dog, animal)

bruno.speak() // Woof!

What is the difference and is one way considered the "right" way?

Upvotes: 8

Views: 1982

Answers (1)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93193

Object. setPrototypeOf

 function(obj, proto) {
  obj.__proto__ = proto;
  return obj; 
}

Object.assign:

function(target, ...varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };

Thus , setPrototypeOf is just assign __proto__ of target to source, However, assign loops through argument(i) keys and override its values by argument(i+1) values according to keys.

Upvotes: 5

Related Questions