I was trying to understand OOP model of JavaScript, so I was reading this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
The following code was interesting:
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.gender = '';
var person1 = new Person('Male');
var person2 = new Person('Female');
//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male
What was interesting and not clear to me is this line:
Person.prototype.gender = '';
I didn't understand so I tested the code both with that line and without it.
The code is working fine in both conditions.
So my question is:
Why did the author add that line?
The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default.
Note: Not all Function objects have the prototype property — see description.
Whenever we create a JavaScript function, JavaScript adds a prototype property to that function. A prototype is an object, where it can add new variables and methods to the existing object. i.e., Prototype is a base class for all the objects, and it helps us to achieve the inheritance.
The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.
You should not set data on the prototype. A lot of times people who come to JavaScript from classical languages attempt it to emulate classical inheritance, but the assymetric nature of the prototype chain (setting is always local but getting climbs up the chain) means that it's impractical. For more information about prototypical inheritance, click here.
The prototype is for sharing functionality across instances. Put functions there instead. For sharing data, see this answer.
That article putting gender on the prototype is mistaken. This is why in ES6, maximally minimal classes set functions on the prototype, but not data members. See this article on why to avoid data on the prototype.
I've fixed the MDN article, nice catch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With