Search code examples
javascriptprototypeprototypal-inheritance

Prototypal inheritance: Object.create vs Object.assign


I am currently reading Kyle Simpson's You Don't know JS, trying to understand the whole prototype pattern.

It says we can achieve prototypal inheritance between Foo and Bar as follows:

      function Foo(name) {
        this.name = name;
      }
      
      Foo.prototype.myName = function () {
        return this.name;
      };
      
      function Bar(name, label) {
        Foo.call(this, name);
        this.label = label;
      }
      
      // here, we make a new `Bar.prototype`
      // linked to `Foo.prototype`
      Bar.prototype = Object.create(Foo.prototype);
      
      // Beware! Now `Bar.prototype.constructor` is gone,
      // and might need to be manually "fixed" if you're
      // in the habit of relying on such properties!
      
      Bar.prototype.myLabel = function () {
        return this.label;
      };
      
      var a = new Bar("a", "obj a");
      
      console.log(a.myName()); // "a"
      console.log(a.myLabel()); // "obj a"

I understand the link is made in the line

Bar.prototype = Object.create(Foo.prototype);

so that Bar's prototype points to an object whose prototype is Foo.prototype.

I was wondering why don't we just do this:

Bar.prototype = Object.assign({}, Foo.prototype);

We achieve the same result and now we have one level of prototype chain lookup for all methods instead of two.


Solution

  • We achieve the same result

    No, we don't. Bar.prototype would then not inherit from Foo.prototype, instead it would have its own properties. Sure, the values from Foo.prototype would be copied over, but that's just a snapshot of Foo.prototype from the time Object.assign was called instead of a live connection.