Notes

Prototypal Inheritance in JavaScript with code examples

Edit on GitHub

JavaScript
2 minutes
 1const obj = {
 2  firstName: 'Aamnah',
 3}
 4
 5const protoObj = {
 6  lastname: 'Awesome',
 7}
 8
 9const protoDaddy = {
10  age: 27,
11}
12
13const protoGrandDad = {
14  occupation: 'Software Engineer',
15}
16
17const protoGrandGrand = {
18  hobbies: ['playing ukulele', 'netflix and chill', 'learning the art of code'],
19  isAwesome: true,
20}
21
22Object.setPrototypeOf(obj, protoObj) // make obj inherit from protoObj
23Object.setPrototypeOf(protoObj, protoDaddy) // make protoObj inherit from protoDaddy
24Object.setPrototypeOf(protoDaddy, protoGrandDad) // make protoDaddy inherit from protoGrandDad
25Object.setPrototypeOf(protoGrandDad, protoGrandGrand) // make protoGrandDad inherit from protoGrandGrand
26
27console.log(obj) // you get the ENTIRE CHAIN of prototypes inherited
28/*
29[object Object] {
30  age: 27,
31  firstName: "Aamnah",
32  hobbies: ["playing ukulele", "netflix and chill", "learning the art of code"],
33  isAwesome: true,
34  lastname: "Awesome",
35  occupation: "Software Engineer"
36}
37*/
 1/*
 2Prototypal Inheritance in JS
 3.__proto__ is ES6
 4Object.prototype() is ES5
 5*/
 6
 7let johny = {}
 8let animal = {
 9  kind: 'human',
10}
11
12console.log(animal)
13/*
14[object Object] {
15  kind: "human"
16}
17*/
18
19console.log(johny) // [object Object] { ... }
20
21// add the `animal` object to the prototype of johny
22johny.__proto__ = animal
23
24console.log(johny)
25/*
26[object Object] {
27  kind: "human"
28}
29*/
30
31console.log(johny.kind) // "human"
32console.log(animal.isPrototypeOf(johny)) // true
33
34animal.kind = 'dinosaur'
35// `johny` will change it's kind too because it is inheriting from `animal`
36console.log(johny.kind) // "dinosaur"
37
38// updating (overriding) the property
39johny.kind = 'buffalo'
40console.log(johny.kind) // "buffalo"
41console.log(animal.kind) // "dinosaur"

The myriad ways of assigning prototypes..

 1// Various ways of assigning prototypes
 2
 3var john = {}
 4john.__proto__ = animal // ES6 way
 5
 6var nancy = {}
 7Object.setPrototypeOf(nancy, animal) // ES5 way, works in ES6 too
 8
 9var sally = Object.create(animal) // ES5 way, works in ES6 too
10
11var jane = Object.create(animal, { food: { value: 'iceacream' } }) // passing it a prototype object to base on, while also default properties for the new object (in the form of an object _describing_ the property)
12console.log('jane: ', jane)
13console.log(jane.food) // "iceacream"

Resources