Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Adding a Prototype

Adding the prototype

how can i add the prototype to this code. I cant understand

1 Answer

So each time the object constructor function is called to create a new instance, it creates a new instance of the methods and properties as well. This duplication of methods can be problematic because it can bloat your code and cause instability for devices with little memory.

The prototype property is primarily used for inheritance, allowing all new instances of that object to inherit and share the same properties and methods declared within object.prototype.

So for this exercise, they want you to rewrite the code so it allows the method to be shared across all new instances of the same object. The method must be declared within the object (in this case Monster ) prototype property.

function Monster(name) {
  this.name = name;
  this.health = 100;
  this.takeDamage = function (){  //Move this method and create Monster.prototype.takeDamage
    this.health--;
  }
}

Hope this helps!