The constructor is just a normal function. This is nothing special.
All functions have the prototype property.
If you write
var myInstance = new MyFuction();
JavaScript does something special with your function when it is executed.
It sets the value of this inside the function body as myInstance . In addition, it creates a link to MyFunction.prototype and saves it as an internal property of myInstance .
When your code executes, the rule to be interpreted is that if you try to access a property on myInstance that it cannot find, it will follow this link to the prototype function and look there. This forms a chain, known as a prototype chain, that extends to Object.prototype .
Here is an example:
function Dog(name, breed) { this.name = name; this.breed = breed;
The snippet above will open, but if you run: console.log(myDog) , you will see that it does not have a conversation method. a conversation method was found in this prototype.
This means that all Dog instances that are created will have a common speak method.
So, if I create another dog, she can also say:
var tommysDog = new Dog('rosco', 'pitbull'); tommysDog.speak();
function Dog(name, breed) { this.name = name; this.breed = breed;
It also means that if I change the value of Dog.prototype.speak at runtime, all instances will be affected.
Note: technically, functions have a constructor property, but this is not so important, and it just bothers you if I try to explain it here.
I suggest you read mozilla docs
In addition, I suggest you read this book . You will learn a lot about the right design.
Also note that this is just one way to achieve code reuse. You do not need to go through prototypes at all. JavaScript actually has methods that allow arbitrary values ββto assign this values ββto functions as arguments.
This means that although my favorite lizard cannot speak normally, I can just take a method from Dog.prototype using a method like call() or apply() . (All functions have these methods because they "inherit" them from Function.prototype .)
function Dog(name, breed) { this.name = name; this.breed = breed;