Nick De Jesus
I like React, love React Native. I play Tekken competitively
by Nick DeJesus
Prototypes are the mechanism by which JavaScript objects inherit features from one another. - What you see after Googling
Console.log(Array.prototype)
const fruits = ['banana', 'apple', 'mango']
fruits.push('orange')
Console.log(Object.prototype)
const fruits = {banana: 'yellow', apple: 'red'}
fruits.hasOwnProperty('banana')
...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'
}
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,
}
By Nick De Jesus