Showing posts with label NAKED JAVASCRIPT. Show all posts
Showing posts with label NAKED JAVASCRIPT. Show all posts

Thursday, June 7, 2012

Naked Javascript - Prototypes and Inheritance

In part 9 of this series Naked Javascript, I am going to talk discuss inheritance in Javascript. In order to understand the concept of inheritance, it definitely hepls to understand the concept behind functions and closures in Javascript. You can check out the previous article on closures and this article on functions to brush up on the basics of these concepts.

Inheritance in Javascript is a bit different from inheritance in other programming languages like Java. The difference lies not only in terms of the syntax but even the implementation is so staggeringly different that it may sometimes not be an easy task to grasp without knowing a few other concepts in javascript.

Lets start from the root of the problem.



Functions

As I have mentioned multiple times throughout the series, functions are first class objects in Javascript. The underlying reason is simple. In Javascript, everything is an instance of the class Object. This is somethign that is taken from Java. The Object class provides a default implementation of several commonly used functions, for example the 'toString' function. Now, to think about it, since all javascript objects need this functionality, they must somehow inherit this function from the object class.

There are 2 important things that you need to remember when dealing with inheritance in JavaScript.
1) Since JavaScript does not have classes, inheritance in JavaScript is achieved by The
2) The mechanism by which two objects are connected in an inheritance hierarch is via the 'prototype' property of objects.

Lets talk about 'prototype'.
When you create any Function in javascript, javascript implicitly defines a new property on that object called 'prototype'. The prototype property is no ordinary property.

Lets see it with a simple example

//Here I have defined a simple constructor function
function Employee(name){
 this.name=name;
}

//Set the default age
Employee.prototype.age = 16;

var emp1 = new Employee('xyz');
console.log(emp1.age);

This is the simplest example that demonstrates the use of the prototype property.

In the first few lines, I defined an ordiary function constructor that would let me create Employee objects. We know that functions are objects. And as I stated earlier, every object gets its own prototype property. Therefore we were able to define a variable called 'age' on the prototype property of the employee class and set its value to 16.

In the last few lines, notice that although we did not declare any property called 'age' on the Employee instance inside the Employee constructor function, we did not get an 'undefined' when we printed the value of the 'age' property on the console. The reason this happened is because we defined a property called 'age' on the prototype property of the Employee function.

What happend here is that when an attempt was made to access a property that is not present on the 'empl' object, the prototype of the constructor function was searched for the property of the same name. So in this case, when we accessed emp1.age, since the JavaScript engine was unable to find the property on the object itself, it tried to lookup a property called 'age' on the Employee.prototype object. This leads us to the conclusion that prototypes are a good place to declare defaults.

Now lets see what happens when we attempt to modify a property on an object that was defined only on the prototype.

function Employee(name){
 this.name=name;
}

//Set the default age
Employee.prototype.age = 16;

var emp1 = new Employee('xyz');
var emp2 = new Employee('abc');
console.log(emp1.age);
emp1.age++;
console.log(emp2.age);
console.log(emp1.age);


When you check the console, you will notice that once you modify the property on the object, that was initially defined only on the prototype, the object will then begin to own a local copy of the property. In our case, when we wrote emp1.age++, this is what we would normally expect the program to do : -

emp1.age = emp1.age + 1;


But, this is what the js engine executed

emp1.age = Employee.prototype.age + 1;


Thats because, before adding doing the addition, emp1.age does not exist. And thats the reason why, on the RHS of the equals operator, emp1.age becomes Employee.prototype.age

The direct implication of this feature is that the prototype property of Functions becomes the most suitable candidate for declaring constants and other properties that will not be modified by instances created by that funcion but which are required for every instace of the class.

function Employee(name){
 this.name=name;
}

Employee.prototype.getName=function(){
 return this.name;
}


This solved the problem of creating a single place to define functions that can be reused by all instances.

However, what if you want a function or a property to be available for all functions?
The answer is pretty simple. Define the property/function on the Function.prototype. For example.

Function.prototype.PI=3.14;

var dummyFunction = function (){};

console.log(dummyFunction.PI);



Note the syntax that we used to access the property PI. We directly made use of the function name. Reiterating myself, this is possible because every function is an object in itself whose constructor is the Function method.


Inheritance

Inheritance is a little bit twisted in Javascript as compared to Java and other similar languages. Thats because in Javascript, objects inherit from objects. The prototype property plays a key role in implementing inheritance. However, it can also be a bit misleading at times. Consider the following example.

In this example, we want to create a Class whose objects inherit certain protperties from another Object. The simplest example to represent this form of inheritance would be

//The doom object is the parent object
//You want to inherit its functions and properties in all
//instances of the MyClass class
var doom = {name:'doom',
   baseMethod:function(){
    console.log('defined on doom');}
   };

//Your class whose instances you want to create
function MyClass(){
 //Some properties
}

//Set the prototype property to the 'doom' object
MyClass.prototype=doom;

//The following invocation wont work because the function is defined on
//the prototype of MyClass. Therefore, MyClass itself
//cannot access the variables of doom directly without
//the prototype property
//MyClass.baseMethod();

//This works because instances of the class
//can access the variables defined in the
//prototype directly.
var mc = new MyClass();
mc.baseMethod();


The secret to the functionality of the prototype is intuitivley simple. Every object in javascript has a hidden property called __proto__. Observe the 2 underscores before and after the word proto. When you create an object in javascript, even if it is an empty object, the value of the '__proto__' property is set to a default object - the Object object, that contains a number of useful methods like toString. Type the following lines in your browser console to verify this

var obj = {};
console.dir(obj.__proto__);


You find that the __proto__ references a default object with a set of functions.

Following our previous example, type the following in your browser console

console.dir(mc.__proto__);


You will find that it points to the doom object. The underlying principle is very simple. When you created an object of type MyClass, something similar to this would have executed under the hood.

mc.__proto__=Myclass.prototype;


And since you have already set MyClass.prototype to reference the doom object, you are all set to inherit the properties of the doom object.


So, whenever you create an object, imagine an invisible link from the '__proto__' of the object to the 'prototype' property of its constructor. For ordinary objects the constructor is the Object class and for your own custom classes, the constructor is the constructor function of your classes. You might want to take a look at this article to learn more about using functions as constructors. 

Another implication of this feature is that, if at any point of time, you want that all objects of your class should inherit a different set of properties, you can simply change the 'prototype' variable in the function name to a different object. That would be equivalent to dynamically swapping the a parent class at runtime, thereby enriching all the existing objects with a new set of functions, which is something is something absolutely cool because thats not something that you can do in languages like Java. What's more is that if you want to change the parent class of only one single object, you can change the '__proto__' property of that object to refer to a different object. Simple, sweet and sexy. 

Thats probably all that I had to say in this post. I hope that you folks loved it. 

Signing Off!
Ryan

Tuesday, May 29, 2012

Naked JavaScript - Defining Classes and Function Instances

In part 8 of the series Naked Javascript, we are going to explore the mystical land of classes in Javascript. Now, coming from a backround with extensive programming in OOPS using Java, the absence of straightforward classes was quite a shocker to me at the start. The syntax, representation and implementation was a complete deviation from conventional methods.

As we learnt in the previous articles, functions are the building blocks of numerous things in javascript. Classes are one of them. In fact, when you define a constructor function, what you are actually doing is creating a function that can be used to construct objects. Lets check out what I mean by looking at an example.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientNewJoinee = new Employee('xyz',99);


If you take a look at this function, there are a number of things that you will note about it.

  1. We make use of the constructor naming convention. 
  2. We make use of the 'this' keyword when assigning property values. The 'this' keyword in javascript is one of those features that may sometimes lead you to lose all your hair if you dont know what you are dealing with(Personal advice : 'this' is highly recommended for hairy women!). I tried to talk about it in intricate details in a previous article. (Make note, hairy women!) 
  3. We passed in two arguments and assigned them as properties on the 'this' object.

Now, this might sound simple at first. Isi'nt it what we always do in other languages like Java?? This is 'suppposed' to be simple right??

Hell no, its not.

Or maybe it is. Lets see what happens.





Case 1 : Doing it the wrong way

You invoke the Employee function as if its just another function, instead of a constructor function. There is nobody who is ever going to stop you from doing such a hideous thing, right? So, lets do it and observe what happens.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

Employee('blah',90);


So what does this do? It works. It executes normally. Really cool, awesome. But what happend to the name and age property that I had passed as arguments? Whos kid did i rename?

Turns out, that you did something totally horrible. What you did was, you created two new properties on the window object.

Now, you should recollect from the previous articles that when you dont specify the context during a function invocation, the function is invoked using the context of the window object which takes the form is nothing but the 'this' keyword inside the function. So, when you invoke the function by directly using the above syntax, you end up creating unnecessary properties on the window object. But thats not something that we want.





Case 2 : Doing it the right way

You invoke the employee function by using the new operator.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientEmp = new Employee('xyz',99);

When you create an object in this way, you are actually creating a new function object, whose constructor is of type 'Employee', and it is this newly created function object that is then used as the context inside the constructor. So, when you are creating properties on the 'this' variable, you are creating properties on your newly created function object. Since you have not explicitly specified any return value, the Employee constructor function returns the value of 'this' variable from the function, which is nothing but the newly created function instance.

Now that solves the mystery of creating classes. But there is much more to this scheme than meets the eye. How do you protect members. Like other programming languages, is there not a way to create private members that cannot be accessed from the outer world? There is a way, but it is not as obvious as it seems.

In the example that we saw, we created two properties on the Employee instance. Both of these properties have public access. i.e. you can directly modify the values of these properties using the object access notation.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientEmp = new Employee('xyz',99);

ancientEmp.age=5;

Oh no, now our ancient emp is younger than the kid next door. And child labor is a crime. We dont wana get into a mess with the authorities, do we? Well, at least not me. So, what do I do that enables me to access the properties on the object but still restrict me from modifying them to incorrect values.

The solution is simple. If you remember, in the previous article, we spoke about closures and scoping in JavaScript. Scoping is a very powerful concept and this is one of the places where scoping is used to mimic the behaviour of private variables in classes.

The JavaBean standard is quite common in the Java world. We can apply the same principle to solve the problem of private variables using getters and setters for our variables and instead of accessing the properties directly.

function Employee(name, age){
 console.log('');
 this.getName = function (){
  return name;
 };
 this.getAge=function(){
  return age;
 };
 this.setName = function (newName){
  name=(newName==true)?newName:name;
 };
 this.setAge=function(newAge){
  age=newAge>14?newAge:age;
 };
}

var ancientEmp = new Employee('xyz',99);

ancientEmp.setName('');
ancientEmp.setAge(5);

console.log(ancientEmp.getName());
console.log(ancientEmp.getAge());

The variables that are declared as function parameters are nothing but local variables in the function and behave like instance variables within the function scope. Due to javascript's scoping rules, they remain available to the function instance as long as the instance exists or are explicitly deleted from the object via some method. Creating getters and setters like this improves decoupling between the various code components.

Now there is a minor issue with creating classes in this way. What happens is that whenever you create a function on an object you are creating a function ONLY for that object. Okey, lets think about it once more. In the first article of the series, I mentioned that when we create properties on objects, the properties are specific only to that object. Now look at our constructor function. What exactly is happening when we are trying to assign getters and setters on the 'this' object? The getters and setters are created exclusively for the current function instance, i.e. the 'this'. This implies that if you are creating a large number of objects, you will end up with each object having its own independent copy of each method and property.





Although, it is highly desirable for each object of a class to be able to save the state of its properties independently, you really don't want to create multiple copies of the same function for each object because that will set your browser on fire and send your users screaming out of their houses. What you want to do is to define a function only once and let all the object point to that function. There are a couple of ways in which you can do that.





1) Use an external function

function calculateSalary(){
 //Sorry for being so random!
 return Math.random();
}

function Employee(name, age){
 //Your stuff
 //
 //End of your stuff
 
 this.calculateSalary=calculateSalary();
}


This is a convenient and perhaps the simplest way that you can enable the reuse of the function. In this way, the calculateSalary property of all the function instances will refer to the same externally defined calculateSalary function. Its simple, its nice. However, there lies scope of improvement. This brings to the point where we have to talk about perhaps the best and the coolest concept in javascript - prototypes (But that's just my opinion. So no bashing please!). I will be discussing javascript prototypes in the next article in absolute details. But until then, we need to learn just a bit to get this example working.





2) Using prototypes

What is a prototype?
A prototype is nothing but a property on an object that is visible to all instances of the object.

Lets demonstrate it in our class example. But before that, I want to reiterate a few points.

  • Functions are objects themselves.
  • Functions can be instantiated to create special objects called function instances, by invoking them using the 'new' keyword.
  • Function objects are also objects, but they have a special property called 'constructor' that identifies the function that was resposible to instantiate this object.
  • Objects can have properties.
  • All objects have a property called 'prototype'.


The prototype property is pretty awesome. When you declare a property on the prototype property, it automatically becomes available to all the instances of that object/function/classs. This means that the prototype is the optimal place to declare a function that needs to be reused by all the objects of a class.

function Employee(name, age){

 this.name=name;
 //Other variables
}

Employee.prototype.getName=function(){
 return this.name;
}

Employee.prototype.setName=function(newName){
 name=(newName==true)?newName:name;
}
Employee.prototype.calculateSalary=function(){
 //Whoops!
 return Math.random();
}

var emp1 = new Employee('xyz');

console.log(emp1.getName());

I simplified the class just for the sake of the example. But if you have noticed, although we eliminated the issue of all the objects having a local vaiable pointing to the getter or setter, we are back to the problem where the property is defined on 'this' itself. So, although this technique is useful for defining the calculateSalary function which does not make use of any properties, it somehow manages to breaks the principle of encapsulation because once again, all the properties will have to be publilcly visible for them to be accessible via the prototype method.




That covers the basics of classes in Javascript. In the upcoming article, I plan to talk the most amazing prototype property and perhaps talk a bit about implementing inheritance in JavaScript. So, until then, stay tuned!

Signing Off!
Ryan Sukale

Saturday, May 19, 2012

Naked JavaScript - Function Scopes, Hoisting And Other Quirks

In this part 7 of the series Naked Javascript, I am going to cover a few interesting quirks about functions and scoping in JavaScript and also talk about a strange feature called hoisting.

The first thing that one needs to know is that in JavaScript, we dont have block level scopes. Instead, in JavaScript, functions are responsible for creating new blocks of scope. Let me elaborate. In other programming languages like java, if you write a block of code like this

public void someMethod(){
for(int i=i;i<10,i++){
 //Some usage of variable i
}
//Compiler error
System.out.println(i);
}


When you attempt to complie this program in Java, you are presented with an error at the line where you attempt to print the value of the variable 'i'. Thats because, once you are outside the for loop, you cannot access the variable 'i'. The scope of the variable 'i' lies only within the code block in which it was declared in Java. Cominng to JavaScript, you need to understand that although javascript makes use of code blocks in the same way that Java does, the scope of a variable lies throughout the function in which it was declared. This means that the following code will successfully print 10 when executed in JavaScript.

public void someMethod(){
for(int i=i;i<10,i++){
 //Some usage of variable i
}
//Prints 10
console.log(i);
}


In the above code, although we printed the value of the variable after it was declared and initialized ,but outside the curly braces, it worked perfectly fine. Now lets take another example.

var n = 1;

function someRandomFunction() {
    console.log(n); // This prints 1.
}


In this function, we declared a variable outside the function. And were were easily able to print its value inside the function, due to closures. Now consider the following piece of code.

var n = 1;

function someRandomFunction() {
    console.log(n); // This prints undefined.
    var n = 100;
    console.log(n); // This prints 100
}


Strange as it may seem, the first console ouput prints undefined. But why? Why is it not able to see the declaration of the variable 'n' that was part of the closure like the earlier example? The reason behind this odd behavior is a feature called 'hoisting'. Hoisting can be explained in a very simple way. For any variable declared within a scope, JavaScript separates the variable declaration and the variable initialization and hoists the declaration to the first line of the scope and initializes the variables at the appropriate lines at which they were initialized by the programmer.

Based upon the above explanation, this is what JavaScript saw when it ran our program.

var n = 1;

function someRandomFunction() {
 var n; //The variable declaration hides under harry potter's cloak. So you cant see it.
    console.log(n); // Now you know why its undefined here
    n = 100; //Now the variable gets initialized.
    console.log(n); // And prints out 100 here.
}


As you see in the code above, the variable was undefined because it was shadowed by the local declaration of the variable in the function. (At least they got that part right!). But then, enter functions! And you have some more nasty code to deal with.

Check out the following piece of code wherein we declare a variable, a function using the conventional function declaration and a second function using the variable style declaration.

function hoistingContainer(){
 console.log(n);
 
 innerOne();
 innerTwo(); //Throws an exception
 
 var n = 100;
 
 function innerOne(){
  console.log('innerOne');
 }
 
 var innerTwo = function innerTwo(){
  console.log('innerTwo');
 }
 
 //This will execute but the code never
 //reaches here because of the previous exception
 innerTwo();
    
}


In the above example, make a note of the different ways in which we declared the two functions. If you run the above code, you would find that the first invocation of the function innnerTwo() leads to an exception whereas the invocation for the function innerOne executes normally. The only difference between these two functions was the way in which they were initialized. Perhaps it can be concluded that when functions are explicitly declared using a variable instead of the conventional notation, the initialization is not hoisted. However, using the conventional function declaration notation, even the function body gets hoisted along with the function declaration.

This implies that if you define functions using the standard notation instead of the variable notation, you can create functions anywhere within a scope and use them at any point within the same scope irrespective of their point of declaration.

The next interesting thing that I want to discuss about is what could happen if you accidentally forget to use the 'var' keyword when declaring a variable inside a scope. Usually, when you declare local variables inside a function, you would use the var keyword. Only the variables that are declared using the var keyword become function local. However, if you accidentally forget the var keyword, javascript will not complain, instead it simply creates a property of the same name in the global scope i.e. on the 'window' object. And as we are already aware, this can have disasterous consequences.

Take a look at the follwing code.

window.constant = 10;

//prints 10, the constant from the global
//window object, 
console.log(constant);

function outerFunction(){

 var name = 'xyz';
 
 //Missing var keyword
 constant = 20;
}

//Invoke the function
outerFunction();

//Prints undefined since name was 
//locally scoped in the function
console.log(name);

//Prints 20, because its value was
//reassigned inside the function
console.log(constant);


Moral of the story, dont forget to use the 'var' keyword when declaring local variables inside a scope.



Scopes and closures.


Closures take extensive advantage of the scoping feature of JavaScript. When a function is declared within the scope of another function, the inner function maintains 'hidden references' to the varibles in the scope in which it was declared. You may also think of it as if functions have their own scope memory. Functions are behaviour. But Javascript functions can not only contain behaviour but also act as a data store. You may like to read another article of mine in which I have elaborated on closures with a couple of examples.



Semicolon insertion.

This is a really strange feature in javascript. The JavaScript processing engine tries to act smart and detect if a semicolon is missing where it should have been put. If it is found to be missing, it simply inserts the missing semicolon and executes the code without any warning. The simplest example, as demonstrated by many other is the problem of semicolon insertion with the return statement. The follwing code returns undefined.

function badStyle(){
 return
 {
  name:'value'
 };
}


function goodStyle(){
 return {
  name:'value'
 };
}

//Runs as expected
console.log(goodStyle());

//Prints undefined
console.log(badStyle());


The second line prints undefined because, since javascript expected that return statement be terminated by a semicolon, it inserted one when it did not see any in the badStyle function. In the goodStyle function, it did not insert one because before the line termination, it encountered a symbol for object literal declaration.

Most of the problems that arise due to the above discussed quirks of the language can be avoided by writing simple yet decently formatted code. Variable declarations at the top, function declarations before using them, and proper opening and closing of curly braces and always adding a semi colon when you are terminating your statements wont only avoid these issues but also make your code readable and understandable. Who knows, just spendinng just a couple of minutes restructuring your code may later save you hours of debugging. 

Stay tuned. There's more to come!

Signing Off!
Ryan

Sunday, May 13, 2012

Naked JavaScript - Closure Dynamics

In part 6 of the series Naked JavaScript, I am going to discuss about the concept of closures in JavaScript. In the previous article, I only briefly mentioned the topic of closures in JavaScript. In this article, we will drill down on the absolute details of this interesting topic. Closures in JavaScropt is a very important concept, and it comes in extremely handy when you are trying to innvoke functions or write classes. Not only is it one of the most important concepts in JavaScript, but it is also mesmerizingly interesting and contributes significantly to the expressive power of this wonderful programming language.

We all know that every programming language has scoping rules for its variables. Javascript takes scoping to a whole new level in the form of closures. The beauty of this concept is most easily understood only by means of examples.





Consider a block of code that is written directly inside the script tag, i.e. in global scope.




Since this block of code was written directly inside the script tag, the varible bingo becomes a global variable. Global variables are variables that are declared on the window object. In this case, since you have not specifed a parent object for bingo, the parent is assumed to be 'window'.

This defaulting logic can cause a huge mess, as we learnt in the previous article, because the size of a program graudally grows with time. And with new features coming in every now and then, you are very likely gonna want to name your variables based upon the real world concepts that they represent. However, declaring variables in the global scope can lead to serious problems because one function may end up reading values set by another function just because they use the same variable name. This is where scoping comes into the picture. However, scoping in JavaScript is a completely different beast. Unlike other programming languages like Java, JavaScript does not support block level scope.

One solution to this problem would be to specify a different parent object for each variable having the same name. For example

//Defined on the global 'window' object
var bingo={name:'xyz'};

//Defined in a nested object
var myObj = {};
myObj.bingo={name:'xyz'};
console.log(bingo.name);
console.log(myObj.bingo.name);


As you see, since we specified the name of the object inside another object, we were able to reuse a variable name without any conflicts. The varables bingo and myObj are global properties. i.e. they have global scope. What this implies is that for your own programs, you can create one single global object and define all your functions as properties of this object. In that way, you can ensure that you clutter the global scope with only a single object. So far so good.





Now lets talk about functions.

When you create a function, you frequently declare new variables inside a function to implement your logic. When these variables are declared, they are declared with a scope that spans the braces that enclose the function. Lets see an example.

function popeye(){
 var msg = 'I love olive';
 console.log(msg);
};

function bluto(){
 var msg = 'I love olive too!';
 console.log(msg);
};


As you see, in our function we were able to reuse the variable 'msg' just because they existed in different scopes. Even this is pretty simple, and of course, works as expected. But wait, there's more.





Enter nested functons.

Unlike Java, javascript lets you create nested functions. The syntax of declaring a nested functions is the same as declaring a normal function. Lets see an example.

function popeye(){
 var msg = 'I love olive';
 
 function printMe(){
  console.log(msg);
 }
 
 printMe();
};


Even this was easy. We just created a new function inside the popeye function and invoked it. But note that you were able to access the value of the variable 'msg' even thought you did not declare it inside the printMe function. So this tells you that nested functions have access to the variables declared in the scope of the outer function. And this nesting can continue further down.

function slimShady(){
 var msg = 'I am slim shady';
 
 function iAmSlimShady(){
  
  function theRealSlimShady(){
   console.log(msg);
  };
  theRealSlimShady();
  
 };
 
 iAmSlimShady();
};
slimShady();


Ok, even this is pretty easy to understand. We create a function slim shady, which declares and invokes an inner function iAmSlimShady which again declares and creates an inner function theRealSlimShady. But the story does not end here. Irrespective of the depth of nesting, an inner function is able to access the variable declared in the outer function. This is what a closure is all about. The ability of an inner function, to dynamically access the values of variables declared in the enclosing function even after the enclosing function has completed its execution is called a closure. The concept of closures actually becomes blatantly obvious when inner function references are accessed from outside the context of the method in which they were declared. Consider this example.

function printer(msg){
 
 function printMe(){
   console.log(msg);
 };
 
 return printMe;
};
var p = printer('Popeye says - Olive is mine');
var b = printer('Bluto says - Your Olive is mine');

p();
b();


What do you see in your console?? What were you expecting? If you have read the other parts of the series, then you will know that I had mentioed earlier that functions are nothing but objects. So, we can simply return a reference of an inner functon from the outer function and thats exactly what we have done. We returned the printMe function from the printer function. Thereby, in our case, both the functions p() and b() refer to the same function i.e. the inner function printMe.

In the first invocation of the function function printer i.e. p, we passed in different string for popeye. In the second invocation, we passed in a string for bluto. And since both p and b refer to the same function - printMe, it may feel that both p() and b() should print the latest value of 'msg' that was passed to the outer function.

Sadly.. Or maybe gladly, thats not what happens. As it turns out, variables declared in an outer function can be accessed by the innner function even outside of the lifetime of the outer function. So even though, upon invocation of the printer function with the argument for popeye's claim, and code execution is completed for the outer function, the inner function will retain a hidden reference to the state of the variable in the outer function. In our case, the variable in the outer function was nothing but the 'msg' argument, which is nothing but a local variable in the printer function.

This implies that if you can preserve the reference to the inner function, you can artificially increase the life of a local variable that was declared in the outer function.





The game of closures gets a bit trickier when used in conjunction with the 'this' keyword. Lets see how that happens using an example similar to the one that we saw above.

function outer(name){
 
 this.name = name;
 console.log('Outer name : ' + this.name);
 
 function inner(){
   console.log("Inner Name : " + this.name);
 };
 
 inner();
};
outer('Popeye');
outer('Bluto');


Observe closely. When I invoked the outer function without specifyng a context, the 'this' keyword in the outer function references the window object and assigns a value of 'Popeye' to the name property of the window object. Even when the inner function is invoked, no context is specified at invocation time, the value of 'this' is also set to the global window object and we can simply print the name.

Now, lets twist this example a bit.

var holder = {};
holder.outer =function (name){
 
 this.name = name;
 console.log('Outer name : ' + this.name);
 
 function inner(){
   console.log("Inner Name : " + this.name);
 };
 
 inner();
};
holder.outer('Popeye');
holder.outer('Bluto');


The only difference in this case was that instead of defining the outer function as a global function, we declared it as a function on the 'holder' object. This sublte change brought about a drastic change in the output. The inner function does not print anything this time. This is what happens instead.

When you are in the outer function, the 'this' refers to the holder object. And you set a name property on it. Simple. But when you invoke the inner function, since you haven't specified any context, the this inside the inner function refers to the window object. And since you have not set any value for a property called name in the window object, all you get is an undefined value.





Lets see another variation of the above example.

var holder = {};
holder.outer =function (name){
 
 console.log('Outer name : ' + name);
 
 function inner(){
   console.log("Inner Name : " + name);
 };
 
 inner();
};
holder.outer('Popeye');
holder.outer('Bluto');



In this case we have removed this 'this' keyword. So both the functions are directly referencing the value of the 'name' argument in the outer function. The inner function is able to access the 'name' variable because of the closure. This can still be made more fun by harnessing the real power of closures.

var holder = {};
holder.outer =function (name){
 
 console.log('Outer name : ' + name);
 
 function inner(){
   console.log("Inner Name : " + name);
 };
 
 return inner;
};
var p = holder.outer('Popeye');
var b = holder.outer('Bluto');
console.log('Invoking Inner functions');
p();
b();


Take a look at the changes made. First of all, the function returns a function reference of the inner function. So now, both the objects p, and b refer to the same inner function. When you create p using the parameter 'Popeye' the local variable 'name' is set to 'Popeye'. And thats the value that is accessible from the inner function. But observe that when you invoke the function with the parameter 'Bluto' the value of the local variable has CHANGED. This is an important point to note.

Later when you invoke the function p(), you are still able to access the value that was passed when the value of 'name' was 'Popeye'. This is what closures do. When you are in a closure, the inner function is able to 'remember' the old value of the outer function that was in its scope. And whenever the inner function is invoked, it works on the reference to the same outer value. So, if you have multiple references to the same inner function that acccesses the same outer value, you can effectively write code as if the values accesed in the inner function are different for different invocations of the same function, as if they are in completely different scopes.

The only variable for which closures is not effective is the 'this' keyword. Thats because each functions has a different value of the 'this' keyword that solely depends upon the way in which the function was invoked. But what if you want to make use of the 'this' reference of your outer functon inside your inner function? Pretty simple. You wrap it in a closure variable. See example below.

var holder = {};
holder.outer =function (name){

 this.name=name;
 var that = this;
 console.log('Outer name : ' + name);
 
 function inner(){
   console.log("Inner Name : " + that.name);
 };
 
 return inner;
};

var p = holder.outer('Popeye');
p();


That was pretty easy. We just created a local variable 'that' and assigned the value of 'this' to that. And thats how the cookie crumbles!





In this article we saw the several different examples of closures. Closures are widely used in almost any piece of code that you read about these days so its important to have a thorough understanding of this concept.

Thats all that I have for this article. I hope you found it useful. There are still a couple of interesting things I intend to cover in the upcoming articles of this series. If you feel lost somewhere, go and check out the previous parts of this series. If not, stay tuned for more!

Signing off
Ryan

Thursday, May 10, 2012

Naked JavaScript - Demystifying The this Keyword and Function Contexts

In part 5 of the series Naked JavaScript, I am going to focus on the the usage of the 'this' keyword in JavaScript. It is extremely important to correctly understand the 'this' keyword it is one of those features of JavaScript where even a small and innocent looking mistake can literally make you pull out your hair if you don't know what you are dealing with.

JavaScript, unlike the name, is not a script like version of Java. In fact, its a completely different beast. And even if it contains keywords and features that 'look' like Java, it does not follow the programming conventions of the the same. I believe that the this keyword is one of those perfect examples of JavaScript where almost everyone new to the language is likely to get confused if they have prior experience of working  with other languages, and therefore make silly mistakes. Some of which can be completely devastating and lead to complicated bugs and sleepless nights.




Lets begin with a simple example example we create an object as follows

var myHappyObject = {
 name : 'MrHappy',
 echo : function (){
  console.log(this.name);
 }
};


Now this seems like a perfectly nice object with a happy little fuction that echoes the value of the 'name' property. But hey! dont forget that 'echo' is nothing but an object that holds a reference to a function. And being a reference, it can be passed to a completely different object. For example, you could do something like this.

var duplicateReference = myHappyObject.echo;


Note that I did not invoke the echo function. I only used a reference to the echo function and assigned it to the variable 'duplicateReference'. After this line, the echo object and the duplicateReference object, both point to the same function that prints the value of the 'this.name' inside the function. But there is a small (or should I say, HUGE) difference! Take a look at the following code.

myHappyObject.echo();
duplicateReference();


Note the output on your console. While the first invocation correctly printed the value 'xyz', the second invocation simply crash landed and printed undefined. At first glance, you might wonder why this is so? Do they not point to the same function? Of course they do. Then why the difference?

In order to understand how the above code works, you need to understand the underlying mechanics of the 'this' keyword and play around with the concept of function contexts.




By default, whenever you invoke a function, a function is invoked in the context of the window object.

function outerFunc(){

 console.log('outer ' + this);

 function innerFunc(){
  console.log('inner ' + this);
 }
 
 innerFunc();
}

outerFunc();



When you invoke the outer function, the first line of console.log prints the value of the window object. That happens because, by default, if you don't specify an object during invocation time, the function call is assumed to be something like window.(). Hence when you are inside the outerFunc, the context is set to the window object, i.e. the value of the 'this' variable is set to the window object. And thats how you get the value of the window in the first line of console.log. 


Similarly, in the second console.log, inside the innerFunc, the value of 'this' is printed as the window object. 

Lets take another example. 


var bingo = {};

bingo.outerFunc=function(){

 console.log('outer ' + this);

 function innerFunc(){
  console.log('inner ' + this);
 }
 
 innerFunc();
}

bingo.outerFunc();


This time we defined the outerFunc as a function on the bingo object. The direct implication of this is that you cannot invoke the function directly. i.e. you cannot directly say outerFunc(). Why? That's because if you do so, the javascript engine will search the window object for the outerFunc() function and since you have defined the function on the bingo object, the search will fail and you get a big slap in the face. However, if you have an itch (in all the wrong places) and still feel like messing with things, you can always invoke it by writing the following code 

window.bingo.outerFunc();


The above example also proves that all objects that seem to be orphaned are not actually orphaned. And that the window object has a strong inclination to play god to all of them. 

But if you notice the console messages, you will also note that even though the outerFunc prints the bingo object as the value of 'this', the innerFunc still prints the window object as the value of 'this'. This implies that context is not inherited. i.e. when functions that are defined inside of a function and invoked inside the function itself, they are oblivious of the value of the 'this' keyword in the outer function. Instead, they get their own copy of the 'this' keyword which depends solely on the way in which the inner function was invoked. 

This odd behavior can have serious implications if not understood properly. 



Lets take a look at our previous example of myHappyObject. Lets redefine the object so that it looks something like this. 

var myHappyObject = {
 name : 'MrHappy',
 rename : function (name){
  this.name = name;
  console.log(this.name);
 }
};


Lets try to do the same things that we did earlier and create another reference to the rename function. 

var duplicateReference = myHappyObject.rename;


So far so good. But there is something very nasty in the piece of code that follows as a consequence of the above assignment. Lets try to invoke both the function references and see what happens. 

myHappyObject.rename('abc');
duplicateReference('garbage');


The code executes smoothly without any errors or warning. It even renames the 'name' property of the myHappyObject to 'abc'. Thats what the first line of code does. But then, what does our second invocation of the duplicateReference do? This function also sets the 'name' property of an object to 'garbage'. But for which object does it set the name property?? I hope that you might have guessed the answer by now. Its our very own window object. What happened over here is something very evil. I say evil because it might not have been your intention to add garbage to the window object but because of the way in which the code was invoked, you accidentally created a property called 'name' on the window object and assigned to it the value 'garbage'. 

What if there was already an existing property called 'name' on the window object and it was being used elsewhere. Our little piece of code would probably lead to a bug that would have been extremely difficult to trace. So remember that whenever you make use of the 'this' keywords, pay careful attention to the manner in which the functions are being invoked. 

Another point to be noted is that although we created a duplicateReference to the rename function, you cannot invoke it using myHappyObject.duplicateReference('abc'). The reason is simple. The myHappyObject does not have any property called duplicateReference. Hence the invocation is invalid. However you can always do something like the following code 

duplicateReference.apply(myHappyObject,['yay'])

//The above code is equivalent to
//myHappyObject.rename('yay');


The code in this case becomes equivalent because when you make use of the apply function, the first parameter behaves as the context of the function and hence is the value of the 'this' keyword inside the function. 



Also there was a case where we talked about the inability of an inner function to access the value of the 'this' keyword present in the outer function. That statement, however, is not entirely true. JavaScript has a extremely beautiful feature called closures that makes so many things possible that it makes you go both wild with madness as well as excitement at the same time. And that's what I am going to talk about in the next part of this series. 

So stay tuned, and stay awake. 
For, the fun....
Has only just begun. ;) 

Signing Off

Ryan

Wednesday, May 2, 2012

Naked JavaScript - Constructor Functions

In the part 4 of the series - Naked Javascript, we are going to take a deeper look at Functions in Javscript and explore its twisted syntax and various implications. In the previous article, we learnt about the different ways in which you can invoke functions. In this part, we examine the stuff that is responsible for creating functions in JavaScript.

Functions in JavaScript are fantastic. Not only are they used to execute functionality, but they are also used to create other objects and functions(Yes, you read that right). Functions are means by which you implement a very significant feature of the language - inheritance. We will be talking about the details of inheritance later. For now, lets continue exploring functions.

Like all amazing and awesome things in the world, when you talk about functions in Javascript, there is more to it than meets the eye. The real way to figure out what more is out there is by firing up your browser console and dissecting it bit by bit.

Lets first try to answer a very basic quesion. What exactly is a function? Well, a function is nothing but a Javascript object. Yes I know that I have said that numerous times in the previous parts of the series, but believe me when I say that it is impossible to stress this point any less.

However, functions are objects with a few special features that makes them stand out from ordinary objects. In order to understand what functions are you first need to know who creates functions.

In javascript, in order to create objects, all you need to do, is define a constructor. Unlike other programming languages(e.g. Java), you dont need any special wrapper around a function, i.e. your constructor does not have to defined inside of a class. A constructor is just an ordinary function. For example

function Employee(){
 //blah blah
 console.log('Employee function');
};

This is a simple constructor function. There is nothing special about this function. The only thing that is different here is the fact that we followed a different naming convention by capitalizing the first alphabet of the function name. This convention is recommended and important when you are declaring constructor functions because it lets others differentiate between ordinary functions and functions that are designed with the intention of be used as a constructor function.

Now this function does not seem to be doing anything special. But in Javascript, you can do something totally strange. You can create instances of functions. For example, once you have declared a employee constructor function like the one above, you can do somethig like this.

function Employee(){
 console.log('Employee function');
};

var emp1 = new Employee();

The syntax is both befuddling and amusing. Lets try to understand the what exactly is happening under the hood here when we invoke a function along with a new operator.

This syntax of invoking functions that are meant to be constructor functions was designed to appeal to Java programmers. When you invoke a function using the 'new' keyword, the runtime creates an empty object and passes that object to the function. That object then becomes the value of the 'this' keyword inside the function. I will be covering the 'this' keyword in JavaScript in details in a later part of this series. But for now, assume that when invoked using the 'new' keyword, the 'this' inside the function behaves similar to the 'this' keyword used in Java. Once the function finishes its execution, the function automatically returns a reference to the 'this' even though you did you explicitly write a return statement at the end of the function. Note that had you invoked the Employee() function without the 'new' keyword, no new object would have been created, and our Employee function would have returned nothing without an explicit return statement.

After the function execution, the variable emp1 now points to the newly created object. You can think of this object to be an instance of the function. I say so because if you try to execute 'emp1 instanceof Employee', it returns true. The 'instanceof' keyword is an easy way to determine the name of the function responsible for constructing an object.

Not only that, every object has access to a property called 'constructor' that tells you about the constructor of that object. For example, you could do something like this.

function Employee(){
 console.log('Executing Employee function');
};

var emp1 = new Employee();
var dummy = {};

console.log(dummy.constructor);
console.log(emp1.constructor);


When you run it on chrome, you would be able to see the following lines on the console.


Executing Employee function
function Object() { [native code] }
function Employee(){ console.log('Executing Employee function'); }


The first line is the normal console.log that was executed when you created a new function object. Thats not much of a mystery anyways. But then, you see another line that says "function Object() { [native code] }". This comes from the log of dummy.constructor. And then in the next line, you see all the dirty little details of our own 'Employee' function. (This point should give you ideas!).

Ok, now that we understand how to create a custom constructor function and create instances using the constructor function, lets have some more fun with functions.

Remember when I said that, that functions are objects too?. And this directly implies that there has to be some constructor function that constructs functions(Tongue twister alert!). Dare to explore? Yes sir!

function Employee(){
 console.log('Executing Employee function');
};

console.log(Employee.constructor);


Turns out that there is a function called "Function" that does the magic of constructing functions for us(This should be your Eureka moment, ryt!! Or, maybe its just me).

So we have a function that creates other functions and it is aptly a function called - "Function". Also note that the naming convention for a constructor function is being followed here. Hey, guess what? Even anonymous functions have the same constructor. Of course they do, since they are functions too(Love that rhyme, dont you?).

console.log((function noname(){}).constructor);


Well, am gonna let curiosity kill the cat and find out who makes the Function function too, because hey, even thats an object, ryt?

console.log(Function.constructor);



It seems that the Function function creates itself. (Ok, now the cat's dead ). 


Now that you know that a function creates a function, this gives you the ability to formulate a new syntax to create functions. 


var dynamicFunction = new Function();


However, the function that we just created is not of much use in this way, because we don't have a function body. But hey ho!, you can create your function with full fledged parameters and the function body as shown in the example below. 

var nowThisIsWeirdButCool = new Function('p1','p2','console.log("Stripping "+p2+" "+p1)');
nowThisIsWeirdButCool('Naked','Javascript');


As you can see, this is a pretty convoluted way of defining functions, but still, it certainly is one of the ways in which you can choose to create functions in JavaScript. Amazing right? But, note that is a really BAD BAD BAD way to create functions because functions created using this technique make use of the sacred JavaScript function 'eval' in order to evaluate the definition of the function body provided as a string parameter at runtime. The use of the eval() function is considered to be evil. ( Need I say that the two words even rhyme to a certain extent. See my point?). 

To conclude, this post uncovered a few more aspects of functions in JavaScript. As I said before, functions are the building blocks of so many things in JavaScript, that is is quite impossible to talk about anything in JavaScript without talking about functions and their various idiosyncracies. 

However, this is all that I have for this part of the series. There's more coming. Stay tuned for the next! 

Happy Programming :)
Signing Off

Ryan

Wednesday, April 25, 2012

Naked JavaScript - Function Access And Invocation

In part 3 of the series Naked Javascript , we are going to talk a little more about functions in Javascript. In the previous article, we just got a basic introduction to JavaScript functions. In this part and the parts that follow, we are going to rip them apart.

Ok, the first thing that you need to know is that - Functions are Awesome. And thats with a capital A(and a capital F!).




In Javascript, functions are first class objects. A function is an object with a special ability - the ablility to be invoked. There are basically 4 ways in which you can invoke a function.

1) The usual way


function boring(msg){
 console.log('oh, this is so so conventional '+ msg);
};

boring('You are killing me!');


2) The unusual way - anonymously


(function cool(msg){
 cool('Do you think that I am cool? ' + );
})('Totally!');


3) Using the Call method


function callMe(msg){
 console.log('Thanks for calling us ' + msg);
}

callMe.call(this, 'Yea, right..');

The syntax for the call is pretty straightforward. The first argument is the context in which the function is to be invoked. The remanining arguments, that you provide as comma separated values is are sent as arguments to the function.


4) Using the Apply method


function applyMe(msg){
 console.log('Do you want me to apply something? ' + msg);
}

applyMe.apply(this,['yes']);

This syntax is similar to the call syntax. The only difference being the fact that you need to pass an array as the parameter to the function instead of a comma separated list as you did in the syntax for call.




We saw the first two techniques in the previous post. But what makes the last 2 techniques so awesome? The answer lies in understanding the concept of a function context and a better understanding of the syntax of accessing properties in Javascript.

Lets talk about the object syntax first. As we saw earlier, functions can be declared on objects as if they are normal properties. In fact, they are normal properties(albeit on steroids, but thats a secret...). Now, the world and its mother knows that one can access properties of objects using the dot operator. But thats convetional and not to mention, dead booring(because we do it all the time). Javascript to the rescue! Javascripts makes things a bit more interesting for us by allowing you to access objects using a different syntax, like a map. For example, check out the code below

var bingo = {name:'xyx', desc:'I am Mr Bingo'};

//The uncool way of accessing a property of an object
console.log(bingo.name);
//The cool way of accessing a property of an object
console.log(bingo['desc']);


Note the special syntax that we used to access the desc property. We simply used the property name as a string in inside the brackets and were able to access the value of the property. This means that objects can be accessed as if they are key-value maps. This is a really cool feature when it comes to functions because functions are objects too. And that means that even they can be accessed via the same technique. This makes it possible to write something like this

var bingo={};
bingo.sayHello=function(){
 console.log('hello');
};

bingo.shout=function(){
 console.log('Scream at the top of my lungs');
};

function doAsISay(funcName){
 bingo[funcName]();
}

doAsISay('sayHello');
doAsISay('shout');


Did you see that!! You can dyanmically pass the function name as a parameter. So you can invoke a function at runtime and not even need to know its name. The doAsISay function acts as a function invoker and invokes any function that is available on the bingo object.




An advantage of using the map syntax for accesing object properties is that it lets you use reserved keywords as keys without the runtime complaining about it. Althouth, I dont think it makes good sense to use keywords as object properties since no matter what programming background you come from, watching a keyword being used anywhere always tends to trigger a train of thought that may not be on the same track of the program that you are working on. However, in a few corner cases, if you do find the need to use reserved keywords as object keys, you are more than free to do so.

We are still not done with functions. Functions are the heart of Javascript, and like all matters of the heart, this one will take its time too. In the next article, I am going to contine with functions and give them another shot to exhibit their awesomeness.

Happy Fungramming!
Ryan

Wednesday, April 18, 2012

Naked JavaScript - Function Basics

After talking about the basics of objects in the previous article, in part 2 of this series - Naked Javascript, we will discuss a little more about objects, their properties and take a sneak peak at functions in javascript.

As we learnt in the previous post, in Javascript you can create objects of the same class but each object can have a different set or properties. Properties can be defined on javascript objects even after they have been declared and used any number of times. For example, you can do this in javascript.

var bingo = {name:'xyz'};
bingo.says = 'hello';
bingo.volume = 5;


As you see, you can add properties to a javascript object even after the object has been declared and initialzied. This is something that cannot be done in Java because each object in Java MUST confirm to the structure of the class of which it is an instance. This feature of being able to dynamically create new properties for existing objects in javascript is called expandos.

If javascript allows you to create expando properties, it also lets you delete them dynamically. Here's how you would delete a property from a javascript object.

delete bingo.volume;


The above statement will delete the volume property on the bingo object thereby clearing the memory occpied by the object's value.

Not only can you declare properties on javascript objects, but you can also declare functions. It would'nt be too far fetched to say that functions are the actual building blocks of javascript.





Functions can be defined in Javascript in a couple of ways.

1) The not so cool way

function doSomethingCool(){
 console.log('I do something mindblowingly cool');
}


2) The cool way - Anonymous functions

function (){
 console.log('My parents forgot to name me!');
};


As you see, an anonymous function has no name(and hence the name 'anonymous' functions! Now that kinda reminds me of the saying - those that have nobody have god). There are many ways in which you can use anonymous functions. But before you start using functions - anonymous or non anonymous, you need to make a clear mental note of one point - Like everything else in javascript, functions are objects too! which means that you can assign it to a variable(huh?).

Lets try to build upon the above 2 examples annd try to assign these functions to variables.

function doSomethingCool(){
 console.log('I do something cool');
}

var makeSomeNoise = doSomethingCool;


Oh! Scary! Well, if you've ever worked with Java, then it might be. However there are some similarities between the two languages. When you assign the function doSomethingCool to the variable makeSomeNoise, you are simply creating another reference to the function. Now both the objects - makeSomeNoise and doSomethingCool refer to the same function. That is why, if we wished to, we could rewrite the first Method of function declaration using the second syntax! See the code below

var doSomethingCool = function(){
 console.log('I do something cool');
}


This way of declaring the function doSomethingCool is exactly equal to the Method 1, the only difference being the syntax. The point to be noted here is that a function name is actually nothing but a variable declared in the local scope.

Although the 'not so cool way' of defining functions is extremely convenient to use, the above syntax in which you assign a variable to an anonymous function makes it extremely easy to always remember that a method name is nothig but a javascript object, albeit not an ordinary one. I will elaborate more about that in the upcoming articles.





Now that you know that function names are actually objects, you can do some weird stuff with it. Something that you could have never do using Java. For example, take a look at the code below

//Define the function
function doSomethingCool(){
 console.log('I do something cool');
}

//Invoke the function
doSomethigCool();

//Assign the function name to point to a different function
doSomethingCool = function(){
 console.log('I do something hot');
}

//Invoke the function again
//This time the function will print a different message
doSomethingCool();


Check your browser's console to verify the output. (Just in case you dont know, if you are using Google Chrome you can press F12 or Ctrl+Shift+I to open the chrome developer tools and click on the "console" tab. If you are using Firefox, you need to install the Firebug extension and then you can press F12 to get the firebug console and then select the "console" tab to view the console messages)

Another cool thing that you might want to know about functions is the way in which it is invoked. In the above examples, we created a few functions and assigned names to them. After that we were able to invoke them using the ordinary function invocation syntax. But what do we do if we want to invoke an anonymous function? The solution is simple(and interesting!)

(function(){
 console.log('I am anonymous');
}) ();


Notice the braces that enclose the anonymous function definition and the bracecs that follow the function name. Using the above syntax, you can invoke not only an anonymous function, but any function. lets see an example.

var usefulStuff = (function makeUsefulStuff(){
 var bingo={desc:'My name is Bingo'};
 return bingo;
})();


Observe the syntax closely. I have simply created a function and invoked it. Inside the function, I created a local variable in the function called 'bingo' and that's what I returned from the function. The immediate function invocation causes the return statement to execute. So, now, the variable usefulStuff and the variable bingo point to the same object. Note that in this case, just because we invoked the function immediately, usefulStuff does not reference a function, instead it references an ordinary object that was returned by the function. Its is quite possible that when reading someone else's code you might forget to read the braces. After all, they are so tiny and close together. But, just in case you find yourself expecting one object and actually getting another, remember to look for a sneaky pair of braces somwhere after the function defintion and you might just save yourself a buttload of hair.





Coming back to the topic of declaring functions as object properties, the sytnax is pretty simple. Check out the sample code below

//Create an object;
var coolObject ={};

//Declare a function on the object
coolObject.doSomethingCool=function(){
 console.log('Do something cool');
};


Although we say that we are declaring a function on an object, we are actually doing nothing but creating a new property on the object that refers to a function definition. Which means that you can even do the following.

var coolObject ={};

//Declare a function on the object
coolObject.doSomethingCool=function(){
 console.log('Do something cool');
};

coolObject.doSomethingCool();

//What!! You can even make it a string now! No way!
//But apparently you can!
coolObject.doSomethingCool = 'I am a string';

console.log(coolObject.doSomethingCool);


This seems to work because the property 'doSomethingCool' was nothing but a reference to a function. We can reassign it to anything that we wish to at any point of time.





Well, that covers a few nuances of functions. But there is a lot more cool stuff that we will uncover in the upcoming articles! Stay tuned!

Happy Fungramming!
Ryan

Wednesday, April 11, 2012

Naked JavaScript - Object Basics

In this series- Naked JavaScript, we are going to delve into the gory details of javascript and extensively elaborate on its features like objects, functions, classes, inheritance, prototypes and closures.

In part 1 of this series, I am going to talk about objects in javascript. And since almost everything in javascript is an object, maybe I can say that I am practically talking about the basic fundamentals of the language. In one way, this part is just a foundation for all the rest of the articles that follow in this series.

Javascript deals heavily with objects. It deals with them at so many levels that sometimes its unfathomable if you are used to writing code in 'conventional' languages like Java or C or C#. Everything from functions to inheritance to arrays take on a completely different perspective in Javascript and this makes the language  unpredictable for a to programmers from a different programming background.

Before we begin, there is one important statement that I want to start with. And that is 'Almost everything in javascript is an object.'



That said, lets see how we can create objects.
There are mainly 2 ways in which you can create objects
  1. Using the new keyword.
  2. Literal declaration.


Using The New Keyword

This is something that programmers from conventional languages are quite used to. The syntax is simple and elegant. You just create a new object and assign it to a variable.

var bingo = new Object();


Since I have worked extensively in Java before, I can say that this seems quite straightforward. In Java, the Object class is the parent class of all the classes. In the same way, the Object class in javascript is the main class from which all Objects inherit features. And because everything is an object, the fact that javascipt does not have predefined types seems to be a misnomer. There is in fact one master type, and that type is Object. No matter who you are or what you do, remember that the almighty Object is watching you!

If you are not sure of my previous statement, try this.


var bingo = new Object();
console.log(typeof bingo);
bingo=10;

console.log(typeof bingo);


As you can see above, we used the typeof operator to determine the type of an object. What you also would have noted is that even though bingo is an object, it was perfectly ok for us to assign a numeric value to it. And when we printed out the type of the variable bingo, we got the type as number. There is a very interesting story of inheritance in javascript that makes this possible. Its something that we will be discussing in absolute details in another article. For now, just be happy with the fact that you dont need to worry about the type of an object before assigning a value to it.



Literal declaration

This is perhaps the most common way to declare objects. The reason being, that its so easy that sometimes its baffling that you can even do this.

var bingo2 = {};


This is very easy on the fingers because it saves you a few keystrokes but it is practically equivalent to

var bingo = new Object();


If you are not used to this syntax, you better get used to it. Because to be honest, its not such a bad thing. In fact its pretty cool!



Declaring Properties On Objects

Objects are objects. And objects are meant to store information. However there is is a slight deviation from conventional languages here. When you create objects, you can directly declare new properties on those objects and assign values to them. Unlike Java, where you must have a predefined class where you first define the properties and the methods of the objects that you create, Javascript lets you do things differently. Lets see that with an example.


var bingo1 = {}; //Create an object of type Object
var bingo2 = {}; //Create another object of type Object
bingo1.shouts = 'hey!';
bingo2.says = 'hello';


Observe carefully. In the above examples, although the type of the objects bingo1 and bingo2 are the same, the language permits you to dynamically declare new properties on each of these objects and those properties dont even need to be same. Although the objects seem to be different because the contain different information, the typeof operator returns the same value for each of these variables.

(typeof bingo1==typeof bingo2) //This returns true


This is something that cannot be done in Java where you can have two objects with a completely different set of properties but still belong to the same class. You dont have the blueprint of a class in Javascript.But that does not mean that you cant have classes in Javascript. It just means that the concept of classes works a bit differently in Javascript.



This makes a short introduction to what is meant by objects in Javascript. That said, in this series, we will explore many more amazing features of the Javascript language such as functions, closures, prototypes and the different ways in which all of these ideas intertwine to create the web as we know it.

Happy Fungramming!

Ryan