MARCUS ÖSTERBERG

JavaScript Prototypes

JavaScript Prototypes

Prototypes are scary

JavaScript is a prototype based language as we all know. Lets deconstruct the definition of prototypes in JavaScript.

When you start of learning object orientated programing with JavaScript. You will come in contact with prototypes and prototypal inheritance. I will try to make you a little bit more comfortable with this concept.

A Prototype is a member of an object and can define the inheritance of a instance.
Before we create our own prototype. Lets just see a quick example of how we are already dealing with prototypes on daily basis.

Here’s an array

var x = [1, 2]

x is an instance of Array. x inherits all prototype properties from Array. So we could for example call Array.prototype.map() function on x

x.map(function(a) { return a + 1});
//returns
[2, 3]


Lets create our own prototype. For this demonstration we will be using the constructor pattern.

//Creates a constructor called createCountry
function createCountry(country){
this.country = country;
}
//Lets create a country by calling the constructor with the argument of 'Sweden'
var sweden = new World('Sweden')
//sweden is now an object with the key value pair of country: 'Sweden',
sweden { country: 'Sweden' }


Now we want sweden to say hello to the world. This is where prototypes and the prototype-chain comes into play.

//Lets define our constructor createCountry prototype property
createCountry.prototype.helloWorld = function() {
console.log('I am a country called ' + this.country)
};

createCountry now has a helloWorld prototype property which represents a function. sweden is still an object with the key value pair of { country: ‘Sweden’ } with a prototypal reference of helloWorld.

//Call helloWorld on sweden
sweden.helloWorld()
//returns
'I am a country called Sweden'


The interpreter looks for helloWorld If no references is found it will start to jump up the prototype chain until the request is satisfied In this case helloWorld can be related to sweden via the prototype chain.
If we now add a new country

var canada = New createCountry('Canada')

Same goes for canada, it will inherite the protype properties from createCountry. This is how a prototype and the prototype chain works.

The concept of prototypes and prototypal inheritance can be more stretched. I hope you found this article helpful. If you have any ideas or examples please share below!

Enjoy your code.


comments powered by Disqus
Archive