Reputation: 43
I have been reading about prototype (both the prototype
property that only functions have, as well as __proto__
that all objects have).
My confusion is about why we need prototype
property in the first place.
Take below code snippet:
function Dog(breed) {
this.breed = breed;
}
let dog1 = new Dog('chow');
The way I understand, functions are also objects in JS. Meaning Dog function is actually an object. A "function object".
So why isn't __proto__
of dog1, simply the Dog "function object"? Why is it necessary to have another object, "Dog.prototype", as an intermediary?
Instead of:
dog1 -> Dog -> global Object
We are doing:
dog1 -> Dog.prototype -> global Object
↘
Dog -> global Function Object
Related question I found in meantime: Why is there a need for prototype objects (in functions)?
Upvotes: 0
Views: 164
Reputation: 54
Update: So I was looking into inheritance myself and came across this article you may find interesting - https://www.educba.com/inheritance-in-javascript/. In particular these paragraphs:
In JavaScript, when creating an object, it creates a link instead of copying behaviors or properties that usually happen in Object-oriented programming languages. In Java, the parent-child class is a separate entity where the properties/behaviors of the parent class are copied into the child class.
A similar kind of linkage gets created in the case of inheritance of class as well. This pattern is called Behavior Delegation Pattern, commonly referred to as prototypal inheritance in JavaScript. Since a copy is created in Java, all arrows are drawn downwards (properties and behaviors flowing down), whereas, in JavaScript, the flow is upwards.
I think this answers your question, but either way it's an interesting read.
Original Answer:
There's an excerpt in this article I found that you may find interesting:
There is something misleading in JavaScript regarding prototypes. The prototype of an object is not the same thing as the prototype property of the object. The former is used when looking up non-existent properties in the prototype chain. The latter is used for objects created using new, it will be the prototype of the newly created object. Understanding this difference allows you to fully understand the prototype property in JavaScript. The value holding the prototype of an object is sometimes called the internal prototype link. It's also been historically called proto, a name that has some controversy. To be politically correct, it can be called the value that's returned from Object.getPrototypeOf(...).
source: https://bytearcher.com/articles/understanding-prototype-property-in-javascript/
The MDN docs state that proto is also deprecated, so may be worth reading their article too: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Upvotes: 1