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 trialjohn larson
16,594 PointsHow is "Dice.prototype.roll" more efficient than "function diceRoll"
We went through a lot of cajoling to get to this point so my question is this:
// how is this
Dice.prototype.roll = function(){
var randomNumber = Math.floor(Math.random() * this.sides) + 1;
return randomNumber;
}
// any more efficient than this
function diceRoll(){
var randomNumber = Math.floor(Math.random() * sides) + 1;
return randomNumber;
}
1 Answer
Steven Parker
231,269 PointsPrototype function code is shared among all instances.
If you encode a method directly in the constructor, all instances of that class will have their own copy of of the method code.
By using the prototype to define the method, all instances will share the same bit of code, saving on memory and instantiation time.
john larson
16,594 Pointsjohn larson
16,594 PointsThanks Steve. I don't fully grasp that, but it's enough of the tip of the iceberg to hold on to.