[Fix] Object Oriented Programming: Remember to Set the Constructor Property when Changing the Prototype (#34569)
This commit is contained in:
		
				
					committed by
					
						 Kristofer Koishigawa
						Kristofer Koishigawa
					
				
			
			
				
	
			
			
			
						parent
						
							a5c9a8d4a1
						
					
				
				
					commit
					56ded4174c
				
			| @@ -6,8 +6,8 @@ challengeType: 1 | |||||||
|  |  | ||||||
| ## Description | ## Description | ||||||
| <section id='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>: | 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>console.log(duck.constructor)<br>// prints ‘undefined’ - Oops!</blockquote> | <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: | 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> | <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> | </section> | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user