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

What is more efficient when we use constructors; a prototype or a referenced function?

Referenced Function

function diceRoll() {
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
  return randomNumber;
}

function Dice(sides) {
  this.sides = sides;
  this.roll = diceRoll;
}

var dice = new Dice(6);

Prototype

function Dice(sides) {
  this.sides = sides;
}

Dice.prototype.roll = function() {
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
  return randomNumber;
}

var dice = new Dice(6);

Thanks,
Yuval Blass.

@stevenparker

1 Answer

Hi yuvalblass,

If there is any actual difference between the two β€” in terms of time and space complexity β€”Β that difference will be negligible. I can't think of a single instance when such a trivial discrepancy would become a matter of concern to a JavaScript developer. After all, the two modes of creating object methods that you are comparing are essentially identical. I'd be interested in hearing if anyone has an actual answer for this though.