I was reading up on prototypes and constructor functions in Javascript and came across the snippet below on MDN:
const personPrototype = {
greet() {
console.log(`hello, my name is ${this.name}!`);
}
}
function Person(name) {
this.name = name;
}
Person.prototype = personPrototype;
Person.prototype.constructor = Person;
What I am confused about is the last line: setting the constructor property within Person.prototype to the Person constructor. Here is MDN's explanation:
The last line (Person.prototype.constructor = Person;) sets the prototype's constructor property to the function used to create Person objects. This is required because after setting Person.prototype = personPrototype; the property points to the constructor for the personPrototype, which is Object rather than Person (because personPrototype was constructed as an object literal).
When I run this code in my console without the last line, there doesn't seem to be any errors. I am confused about why the Person.prototype.constructor must be set to Person and not left as the default Object. Does it have something to do with instances created by Person? Thanks.