[Fix] Object Oriented Programming: Remember to Set the Constructor Property when Changing the Prototype (#34569)

This commit is contained in:
Aditya
2018-12-14 16:29:35 +05:30
committed by Kristofer Koishigawa
parent a5c9a8d4a1
commit 56ded4174c

View File

@ -6,8 +6,8 @@ challengeType: 1
## Description
<section id='description'>
There is one crucial side effect of manually setting the <code>prototype</code> to a new object. It erased the <code>constructor</code> property! The code in the previous challenge would print the following for <code>duck</code>:
<blockquote>console.log(duck.constructor)<br>// prints undefined - Oops!</blockquote>
There is one crucial side effect of manually setting the prototype to a new object. It erases the <code>constructor</code> property! This property can be used to check which constructor function created the instance, but since the property has been overwritten, it now gives false results:
<blockquote>duck.constructor === Bird; // false -- Oops <br> duck.constructor === Object; // true, all objects inherit from Object.prototype <br> duck instanceof Bird; // true, still works</blockquote>
To fix this, whenever a prototype is manually set to a new object, remember to define the <code>constructor</code> property:
<blockquote>Bird.prototype = {<br>&nbsp;&nbsp;constructor: Bird, // define the constructor property<br>&nbsp;&nbsp;numLegs: 2,<br>&nbsp;&nbsp;eat: function() {<br>&nbsp;&nbsp;&nbsp;&nbsp;console.log("nom nom nom");<br>&nbsp;&nbsp;},<br>&nbsp;&nbsp;describe: function() {<br>&nbsp;&nbsp;&nbsp;&nbsp;console.log("My name is " + this.name); <br>&nbsp;&nbsp;}<br>};</blockquote>
</section>