Let's say I have this object (I mean, constructor function with which I create a new object)
const Person = function (firstName, birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
};
Now, I accidentally realized that if I for example want to add a method on Person I can console.log it before it was defined, so, how is that possible? So, what I mean is: https://routerlogin.uno/
console.log(Person.prototype); //it shows that Person already contains calcAge function before it was defined
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
};
I expected some error because of that, but for some reason everything worked fine.
It doesn't show any calcAge method because at this point in the code, you haven't added it yet. JavaScript does not hoist the assignment of properties/methods on objects.
Afterwards, when you do:
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
};
You're adding the method calcAge to the Person.prototype object. This assignment doesn't need to be hoisted because it's not a declaration - it's just an assignment of a property to an object.
When you create object using contructor , all functions have a property named prototype. When you call a function as a constructor, this property is set as the prototype of the newly constructed object (by convention, in the property named proto).