Reputation:
If we assume this sentence is true: "prototype
is the object that is used to build __proto__
", how Object.create works? If you do:
let obj1 = {
name: "obj1",
}
const obj2 = Object.create(obj1);
How Object.create()
should create obj2.__proto__
from ob1.prototype
when ob1.prototype
is undefined
??
Maybe Object.create()
uses another method of creating prototypical inheritance than constructor or factory functions??
Because, in Object.create()
example above this is true:
console.log(obj2.__proto__ === obj1);
but if we do the same thing with constructor function, this will be true:
console.log(obj2.__proto__ === obj1.prototype);
Constructing the object with the function:
function obj1(name) {
this.name = name;
}
const obj2 = new obj1();
Am I missing something?
Upvotes: 0
Views: 86
Reputation: 138277
Your sentence "prototype
is the object that is used to build __proto__
" only applies to function
s that get called with new
. E.g.
let dog = new Animal();
equals:
let dog = Object.create(Animal.prototype); // <<<
Animal.call(dog);
Prototypal inheritance itself just means that objects contain an "internal" (__proto__
) reference to it's prototype. With Object.create
you create an object whose prototype is set to the object passed. Therefore
let inherited = Object.create(obj)
is rather equal to
let inherited = {};
inherited.__proto__ = obj;
Upvotes: 1