Explaining the prototype with fishes

Everything is an object in JavaScript

 

The few things that aren't objects like the primitives (number, string, boolean...) will temporarily be wrapped as objects when needed.

Primitives as objects

https://repl.it/EAJv/1

JavaScript Objects are not common oop objects

 

There are no classes in JavaScript because JavaScript is a prototype object oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes.

The Prototype way

What The H... prototype inheritance means?

 

Prototype is like the evolution for objects, it chains one object to another, sharing the information stored which is also dynamically linked to the parent

Basic example (not for production)

https://repl.it/EALD/0

Basic example (little better for production)

https://repl.it/EBDj/3

There should be a better way to create fishes

 

Constructor functions are the most used way in JavaScript to construct prototype chains.

The fishes factory

https://repl.it/EBEf/1

Testing more things

https://repl.it/EBEf/2

 

so my fishes have colors and sizes, lets make them swim, eat.. sleep

 

so.. here is the thing... functions are objects and objects can contain objects... and those things could be in the protoype

Functions in the prototype

https://repl.it/EBHP/1

What about ES6 classes?

 

So, we have Function Constructors, which have been the common way to build new objects until ES6. sometimes Function Constructors can be confusing to understand (especially if you want to model inheritance). To alleviate this, ES6 introduces the class syntax.

Using classes

https://repl.it/EBIM/0

So are classes different?

ES6 classes just create the same prototype chains we know and love from previous versions of JavaScript, but with a much saner syntax than Function Constructors.

These are the basics, want to go pro?

Why fishes?

 

I am a diver... ;)

Thanks everybody



Adrián Estrada
@edsadr

"Everything looks a way better in a hat"

Explaining the prototype with fishes

By Adrián Estrada

Explaining the prototype with fishes

This deck will try to explain JS prototype using fishes

  • 1,622