function Person(name, age, gender) {
(this.name = name), (this.age = age), (this.gender = gender);
}
Person.prototype.eyecolor ="black";
var myFather = new Person("Singh", "50", "Male");
console.log(myFather.eyecolor);
console.log(myFather);
console.log(Person);
myFather inherits from Person.prototype using
__proto__
which links myFather to Person.prototype
(myFather.__proto__ === Person.prototype
) and this Person constructor function inherits from Function.prototype
and this Function has inherited from Object.prototype
and this is why it's said everything in javascript is essentially an object.
Have I understood this thing right? I have commented on what I have understood here in Prototypes in JS. At this point in time, I don't know the practical use of this concept. Maybe when I learn more I might see some use of it.
Yes, you have understood this correct. This concept is called the prototype chain in Javascript.
JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
Basically this will go all the way back until it reaches the object object, which all Javascript types inherit from, whose __proto__
is null.
Please note that there are two properties existing, which are basically the same: __proto__
and prototype
. The distinction is that only functions have the prototype
property, while all objects have the __proto__
property. The __proto__
property is non-standard, but most browsers have it implemented, so it is save to use.