JavaScript Prototypes

 

by Nick DeJesus

What are prototypes?

Prototypes are the mechanism by which JavaScript objects inherit features from one another. - What you see after Googling

Array.prototype

Console.log(Array.prototype)

  • push()
  • pop()
  • map()
  • reduce()
  • filter()
  • etc..

const fruits = ['banana', 'apple', 'mango']

fruits.push('orange')

 

Object.prototype

Console.log(Object.prototype)

  • create()
  • hasOwnProperty()
  • keys()
  • assign()
  • values()
  • etc..

const fruits = {banana: 'yellow',  apple: 'red'}

fruits.hasOwnProperty('banana')

Other Objects with Prototypes

  • String
  • Number
  • Promise
  • JSON

...And many more

"Why is this important?" - Bootcampers 2019

 

Prototypical inheritance promotes reusable code. Reusability keeps your code consistent, organized and is more performant.

Why don't we use prototypes to build an army of evil robots?

Evil Robot Army

const earl = {
  name: 'Earl',
  weapon: 'laser'
}

const jane = {
  name: 'Jane',
  weapon: 'Buzz Saw'
}
  • Repetitive
  • Not scalable
  • Takes up too much memory

Evil Robot Army

function EvilRobot (name, weapon) {
  this.name = name;
  this.weapon = weapon;
}
const bert = EvilRobot('Bert', 'Laser');

const jane = EvilRobot('Jane', 'Buzz Saw');
console.log(jane);

{
  name: 'Jane',
  weapon: 'Buzz Saw'
}

Evil Robot Army

function EvilRobot (name, weapon) {
  this.name = name;
  this.weapon = weapon;
}
console.log(EvilRobot.prototype)

// {}
console.log(EvilRobot.prototype)

// { whois: function() {...} }
  EvilRobot.prototype.whoIs = function () {
    console.log(`Hi. I'm ${this.name}. I destory humans with my ${this.weapon}`)
  }
bert.whoIs()

// 'Hi! I'm Bert. I destroy humans with a Laser'

Evil Robot Army

EvilRobot.prototype.destroy = function(numOfPeople) {
  return `BRB. Destroying ${numOfPeople} humans with my ${this.weapon}`
}
console.log(bert.destroy(100))

// 'Brb. Destroying 100 humans with my Laser'
console.log(jane.destroy(50))

// 'Brb. Destroying 50 humans with my Buzz Saw'

Prototypes can inherit from Prototypes

function Bird() {
  this.hasBeak = true;
  this.canFly = true;
}

const tweety = new Bird();
function Parrot() {
  Bird.call(this);
  this.canTalk = true;
}

const gandalf = new Parrot();
console.log(gandalf);

{
  canFly: true,
  hasBeak: true,
  canTalk: true
}
console.log(tweety);

{
  canFly: true,
  hasBeak: true,
}

End

JavaScript Prototypes

By Nick De Jesus

JavaScript Prototypes

  • 319