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:
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:
__proto__
-> [[prototype]]
(?)Object.create I can only:
__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!
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));