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