[Fix] Object Oriented Programming: Remember to Set the Constructor Property when Changing the Prototype (#34569)
This commit is contained in:
committed by
Kristofer Koishigawa
parent
a5c9a8d4a1
commit
56ded4174c
@ -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> constructor: Bird, // define the constructor property<br> numLegs: 2,<br> eat: function() {<br> console.log("nom nom nom");<br> },<br> describe: function() {<br> console.log("My name is " + this.name); <br> }<br>};</blockquote>
|
||||
</section>
|
||||
|
Reference in New Issue
Block a user