prototypical inheritance

In JavaScript there are non-primitive types that have methods and properties that can be called on them.

non-primitive types are functions, objects and arrays

example of methods stored on the prototype

properties and methods can be shadowed

This means that properties or methods defined closest to the instance have priority of being called then properties defined in the prototype.

JavaScript

let array = [2];
array.test = function () { console.log('hi') }
Array.prototype.test = function () { console.log('hi somewhere else') }

array.test(); // hi

“hi” was console logged instead of “hi somewhere else” because it was defined closer to the instance of the array that was created.

how to call methods on the prototype

The prototype can be accessed by the proto property.

JavaScript

let array = [2];
array.test = function () { console.log('hi') }
Array.prototype.test = function () { console.log('hi somewhere else') }

array.__proto__.test(); // hi somewhere else

prototype chain

Every object stores a reference to its prototype.

In the previous example the test function was stored on the array and in the Array prototype.

When executing the test method on the array, JavaScript looks for method on the prototype chain starting from the variable instance. When the method is found JavaScript stops looking for it in the prototype chain and uses it.

JavaScript

arr.test() // hi

The prototype chain will look like this for the example above.

instance of variable => array => object => null

You can think of the prototype chain as the way JavaScript looks for a method when it is being called on a object.

JavaScript found the test method on the array instance first, this is why the test method on the array was executed instead of the test method on the Array prototype.

primitive types have object wrappers

JavaScript has object wrappers that you can declare so you have access to methods on the prototype.

JavaScript will automatically “box” wrap primitives values so you have access to methods.

JavaScript

42.toString() // Error

let x = 42;
x.toString() // "42"
x._proto__ // access to proto
x instanceof Number // false

When declaring a variable to a primitive type it will wrap the primitive object wrapper.

In this case we declare the variable to be equal to 42 which then gets wrapped by the Number() object wrapper. This will give us access to the Number prototype.

html
css
the good parts of float and clear

floats and clear are important to know because you never know when you are going to be working on legacy code.

javascript
why JavaScript methods are useful

You can think of a method as an action that a number, string or object can perform or have taken on it.