How to properly use Object.setPrototypeOf()

Viewed 13500

So I've been getting up to speed on some of the newer features of JavaScript and have been reading about Object.setPrototypeOf(). I ran across this bit of code from MDN which deals with inheriting from regular objects. But I'm confused at how they use Object.setPrototypeOf() here. I expected them to write

Object.setPrototypeOf(Dog, Animal) 

as opposed to what the do below. Why do they write it this way?

var Animal = {
   speak() {
     console.log(this.name + ' makes a noise.');
   }
};

class Dog {
   constructor(name) {
   this.name = name;
  }
}

Object.setPrototypeOf(Dog.prototype, Animal);// If you do not do this you will get a TypeError when you invoke speak

var d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
2 Answers

1) Animal is an Object literal
2) Object literal doesn't have prototype property
3) the syntax is

Object.setPrototypeOf(targetObj, sourceObj);
Object.setPrototypeOf(Dog.prototype,Animal);

4) By doing this we are inheriting the properties of
object literal ( Animal) to another literal or constructor(Dog)

5) here the Dog 's prototype is being set from Animal.
this method (Object.setPrototypOf()) sets a reference to Animal's methods to Dog's prototype

Related