Wednesday, November 2, 2016

Prototypes objects constructors the basics

Prototypes is a more efficient way to use methods inside of constructor functions.  It allows you to create methods that can be called for each instance of a particular constructors.

Meaning that:

function Monsters(name) = {
  this.name = name;
  this.health = 100;
  this.takeAHit = function() {
    this.health --;
  }
}

The above takeAHit function has to be run for each time we make a monster.

var bigfoot = new Monsters(bigfoot);
var sharkweek = new Monsters(sharkweek);

if there where thousands of names it would take more computing power and more time call the takeAHit() function for each new name.

Wouldn't it be nice if we could call it once for all of them?

Prototype is what you need!

function Monsters(name) = {
  this.name = name;
  this.health = 100;
  this.takeAHit;
  }
}
Monsters.prototype.takeAHit = function() {
    this.health --;
   }

No comments:

Post a Comment