Javascript
Total 3 posts

Javascript Closures (and why they are useful)

What do you think the output of this function will be?

var mindBoggler = function() {  
  for(var i = 0; i <= 3; i++){
    setTimeout(function(){
      console.log(i);
    }, 1000);
  }
};

mindBoggler();  

You're probably thinking

(1 second)
0  
(1 second)
1  
(1 second)
2  
(1 second)
3  

But the actual output is

(1 second)
4  
4  
4  
4  

How would we fix this to get our desired output?

Continue Reading

Object Oriented Javascript (4 different patterns)

You might have thought Javascript to only be a functional programming langauge, but it's technically both Object Oriented and Functional!!

Today, I will be showing you how to write objects in 4 different instantiation patterns.

  1. Manual creation of an object
  2. Functional instantiation
  3. Functional instantiation with shared methods
  4. Prototypal instantiation
  5. Pseudoclassical instantiation

0. Manual Object Creation with methods

The reason for all of this, is that creating objects manually without a class is tedious. But before we begin, I think it's super important that you realize why these instantiation patterns are important.

Let say you want to create a person named Arian, whose age is 25. You also wanted to create another person object that was named Michael, whose age is 23.

What if you also needed to calcuate what year a person was born in? or if you needed to compare two peoples age?

You might do the following:

var arian = {  
  name: 'Arian',
  age: 25,
  calcBorn: function() {
    var currentYear = new Date().getFullYear();
    return currentYear - this.age;
  }
};

var michael = {  
  name: 'Michael',
  age: 23,
  calcBorn: function() {
    var currentYear = new Date().getFullYear();
    return currentYear - this.age;
  }
};

arian.calcBorn();    // 1990  
michael.calcBorn();  // 1992

var diff = arian.age - michael.age; // 2  

But notice how you had to rewrite the calcBorn function twice!

Continue Reading