Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
Phil Mok Avatar asked Feb 13 '17 19:02

Phil Mok


1 Answers

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.

like image 142
Abdennour TOUMI Avatar answered Oct 04 '22 09:10

Abdennour TOUMI