const personPrototype = {
greet() {
console.log(`hello, my name is ${this.name}!`);
}
}
function Person(name) {
this.name = name;
}
Person.prototype = personPrototype;
Person.prototype.constructor = Person;
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).
so, the personPrototype function is just an object literal, so setting Person.prototype to this object literal needs to be reset as an actual prototype object?
is all that’s happening here is inheriting the greet() method and then resetting the object constructor?
can anyone expand on what’s happening here, please?
The prototype is just a object containing a constructor function and optionally some functions. If we create an new object with const person1 = new Person('Bob'); the constructor in the prototype object is used to build this object and the functions in the prototype object are made available to the object.
When we write a function it automatically gets a prototype object with a constructor function inside (which is a reference to itself). This means after
function Person(name) {
this.name = name;
}
there automatically exists a Person.prototype.constructor which references Person itself. After
Person.prototype = personPrototype;
Person.prototype only contains the greet() function which will be inherited when creating objects with new Person(). When we are now doing
Person.prototype.constructor = Person;
the constructor will be set again to the Person function and the prototype object is valid again.
I hope that clears it up a bit. The whole inheritance topic is pretty complicated. Feel free to ask more questions if you like