I was reading the developer.mozilla.org guide to OOP JS and came across this snippet:
function Person(gender) {
this.gender = gender;
}
Person.prototype.gender = '';
Person.prototype.sayHello = function () {
alert ('hello');
};
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello(); // hello
I don't understand, if (gender) is already defined as this.gender; why do we need to put the Person.prototype.gender = ''; line? I understand it for functions outside of the constructor, but it seems like that line is repeating the this.gender; line. I understand it is creating gender as a property of the Person() object, but doesn't that just repeat the this.gender?
I would appreciate any explanation, I'm new to OOP JS. Thanks!
Perhaps a slightly different syntax may help to define the default you are asking about
The short answer is that the line is only there for a default value, you are essentially doing something like this:
If, you create a Person and you don't pass in a gender, this.gender is set to undefined;
So when you look the property up, it will look up property on the object itself. That will turn out to be undefined, so it will then try to look it up on the prototype and find the empty string which is not undefined.
Therefore, it's only a default value in this case, and it's totally fine to not use this pattern ever and only use prototype for methods, and not values.
By adding
Person.prototype.gender = '';
the Person has a "default" gender persay. It is more like defining a gender for the Person if no gender is specified at instantiation. Keep in mind, settingthis.gender = gender
whengender
is undefined still counts as specifying a value.When it becomes obvious is if you try to delete the
gender
property from your persons. IfPerson.prototype.gender = '';
is omitted, then the following situations can occur:Because
person1
does not havegender
anymore, it cannot reference it in this Person instance, so it will look up its prototype chain at the Person constructor. And it won't find it there because in the constructorthis.gender = gender;
is a instance property. The lookup process continues up the prototype chain until it finds the property.Now consider if we have the following: