If
let variable = new FunctionConstructor();
then variable.__proto__
= FunctionConstructor.prototype
. What is variable .__ proto__
(the object from which variable
is inherited) is clear, but what is equal to the prototype
property of a constructor function is not.
- "What semantic meaning (preferably related to real world objects) does
FunctionConstructor.prototype
have?" - If
let variable = new FunctionConstructor ();
, then, on the one hand,variable
inherits fromFunctionConstructor
(since it was created using the operatornew FunctionConstructor ();
), and on the other hand,variable .__ proto __ = FunctionConstructor.prototype
(again because it was created with thenew
operator), i.e.variable
prototypically inherits fromFunctionConstructor.prototype
. What is the difference between prototypal inheritance and normal inheritance?
It is an object that was created at the time that
FunctionConstructor
was defined. So whenever a function is defined, it immediately gets an object property (prototype
). Some exceptions exist where functions cannot be used as constructors (e.g. arrow functions, members of aclass
definition, ...).This object can be given members like any other object. In old style code you'll often see
FunctionConstructor.prototype.myMethod = ....
. In modern versions you'll see theclass
syntax, which results in similar initialisation of thatprototype
object.This object will serve as a prototype whenever the constructor is invoked with
new
. When such invocation takes place, even before any statement of that function is executed, a new object is created that will bethis
during the function's execution and will be returned bynew
. Thatthis
object will have its__proto__
property set to that prototype object, establishing the prototype chain. So this is the moment that the prototype starts to play its role.No, this is not true. The
variable
will not inherit anything fromFunctionConstructor
.FunctionConstructor
is an object (a function object) with its own prototype (which is not itsprototype
property, but its__proto__
property), and that chain has nothing to do withvariable
at all.It helps to visualise these two independent prototype chains. See How does JavaScript .prototype work?, where I elaborated on this in my answer.
This is true.
There are many differences. Here are a few:
Classical inheritance relies on classes, which provide the template for instances. Classes define a hierarchy, but instances cannot inherit from each other. Prototypal inheritance relies on constructors and their
prototype
property. Prototypes are just objects, and can be modified, classes not.Read more: