Search code examples
javascriptoopinheritanceprototypeprototypal-inheritance

What is a practical advantage of Object.create over Constructor function?


So I am coming from classical OOP language and trying to wrap my head around javascript prototypical style.

Trying to understand the difference between function constructor pattern and Object.create pattern when it comes to:

  1. Scope: private and privilege methods
  2. When to use which in application

Function Constructor I can create private functions and methods as follows:

function Human() {
  this.public = "public accessible variable";
  let private = "private only accessible inside Human";
}
Human.prototype.speak = "hahahaha";

var child = new Human();
Console.log(child.public) // prints
console.log(child.private) // don't print 

Benefits:

  1. Function constructor pattern allows to create public and private methods.
  2. I can access the Human.prototype properties.
    • child object refers to Human prototype __proto__ -> [[prototype]] (?)

Object.create I can only:

  1. Create an object and set its prototype i.e. __proto__ to Human object (instead of Human's prototype)

But so what? What are the practical advantages of directly setting child's prototype to human over constructor function?

Examples of real uses would help!


Solution

  • Calling a constructor function:

     const child = new Human();
    

    is (nearly) the same as:

     const child = Object.create(Human.prototype);
     Human.call(child);
    

    therefore I would not see Object.create as a language feature, but rather as a way to understand prototypal inheritance in JS.

    There are very very limited usecases for prototype chains without constructors. One example would be the deserialization of a Human:

     const serialized = JSON.stringify(child); // Human inheritance gets lost, its a plain object now
    
     const child2 = Object.assign(Object.create(Human.prototype), JSON.parse(serialized));