JavaScript – The this keyword

March 23, 2012 Leave a comment

“this” is one of the most misunderstood construct in JavaScript.  To understand this first lets go through how to create a construction function in JavaScript.  A constructor function is a function which is used to create instances of objects in JavaScript.

You define a constructor function using the same notation that you use to define a normal JavaScript function.  The convention to follow is to capitalize the first letter of the function name.

This requirement is not enforced by the JavaScript language but it is a generally accepted practice and there are many benefits which we will shortly discuss.

Let’s define a constructor function to hold our menu information.

function Menu() {

}

So, in the above snippet you have a constructor function named Menu defined. At present this function doesn’t do anything good.

Let’s see how to invoke this function

var menu = new Menu();

Let’s add some public properties to this function.

function Menu() {
    this.menuName = "File";
}

Let’s create an instance and see how we can use this.

var menu = new Menu();
alert(menu.menuName);

If you run the above code, you should get an alert with a value “File”.  This is not so interesting.

Let’s pass, in the name information to the function.

function Menu (name) {
    this.menuName = name;
}

Now you can call this function as shown below.

var menu = new Menu("file");
alert (menu.menuName);  // You will still get an alert with a value 'file'

Isn’t this interesting now.   Now the point to remember is that nothing in JavaScript prevents you from invoking this function directly.

For e.g.

var menu = Menu("file");

What do you think the output of the above will be if you do an

alert(menu.menuName);

You will get an error similar to “Uncaught TypeError: Cannot read property ‘menuName’ of undefined”.

You can see this in action here

http://jsfiddle.net/rajeshpillai/DC8LZ/embedded/

Why?  Any idea?  Also, there is a side effect to this.   You accidentally created a global variable “menuName”.

You don’t believe me.  Try doing an

alert(menuName);   // OR
alert(window.menuName);

Ok. Lets get a bit deeper into how this thing work.  By default a constructor functions always returns an instance of the function object  on which the “new” is called upon.

If you directly invoke a constructor function without creating a new instance, then that function is executed rather than an object being constructed. So, the return value of that function invocation will be undefined as you are not explicitly returning any value from the function.

So, all assignment to “this”. goes to the global window object and you accidentally create globals.

Always name your constructor function starting with an uppercase.

The primary reason why this is an issue is because JavaScript don’t force you to construct object of constructor function as for JavaScript execution engine there is no difference between the two.

This is where naming convention plays an important role. Name all your constructor function starting with an uppercase letter. This way it will be very easy for you to detect if there is any unintentional misuse of the constructor function. Besides there are certain tools like “jslint” which warns you if you directly invoke a constructor function which has a name starting with uppercase.

Ok, so how to avoid this problem.  What we want is whenever the user uses the Menu function either as direct function call or as a constructor function we need the function to return a menu object to the user.

A simple solution is to return an anonymous object from the constructor function with required properties attached to it.

function Menu(name) {
    return {
        menuName : name
    };
}

We can use this function either by direct call, or through constructor invocation, we will always get the correct object, without creating globals.

Why this works is because constructor function by default returns the instance of the object on which it is invoked.  The other interesting thing is we can return any thing from this constructor function.  We will use this feature to return correct object back to the caller.

var menu = Menu("file");  / called directly
alert(menu.menuName);  // alerts 'file'

var menu1 = new Menu("Help");  // call with new
alert(menu1.menuName); // alerts 'Help'

// alert(menuName);  // See no, globals

this Gets tricky

Take this example below. We have a simple function which returns stock quote. Pretty simple example in this case.

 

function StockQuote() {
    this.quote= "12,13,343,343";
    this.getQuote= function() {
         //this is expected to be a reference to the current instance
         return this.quote;
    }
}

 

Now lets’ say we need to get the quote in the next 3 seconds..

var quote = new StockQuote();
// call the getQuote function in 3 seconds.
setTimeout(quote.getQuote, 3000);

 

Many beginner JS dev may think this may work, but it won’t. It’ll give an error saying that quote is undefined. This is because there is no binding of functions to instances in JavaScript. Whenever the instance isn’t explicitly stated, then “this” becomes windows object (at least in the browser, as js runs in other environment as well). Writing quote.getQuote() indicates that you want “this” to belong to quote, so it will work correctly. However, the setTimeout function only has a reference to that function. When it calls it, after 3 seconds, it is not aware of “quote”, so JavaScript sets this to window.

 

“Fixing” this

There are several ways of forcing this to be what you intend to be and many of them uses some unique features of JavaScript.

The two important ones are

  • apply
  • call

apply is a member of every function. It says “invoke this function on this object (change the context of the object).

An example is shown below.

// These two are same..
quote.getQuote();
// "quote" is the this context you are passing
quote.getQuote.apply(quote);

// you can also do this.
var myQuote = new Quote();
myQuote.getQuote.apply(myQuote);

// The above line does the same thing as
myQuote.getQuote();

 

Before solving the setTimeout problem lets briefly have a discussion on Lexical Scroping in JavaScript.

Lexical scoping allows you to access local variables in a parent function by the child functions. i.e. if a function is defined withing another function, it can access its own local variables as well as those of the function it was defined within.

Now let’s solve the setTimeout problem with Lexical scoping.

var myQuote = new Quote();
setTimeout( function() {
    myQuote.getQuote();
}, 3000);

We created a new anonymous function which we are passing to the setTimeout. Our new function can access myQuote, so it just applies it to the getQuote function.

Solving setTimeout problem using “apply”.

 

var myQuote = new Quote();
setTimeout(myQuote.getQuote.apply(myQuote), 3000);

 

The difference between call and apply is subtle and only varies in the way parameters are passed. apply requires the second parameter to be array which represents the parameters to the function , and call accepts an argument list…

Let’s quickly look at the syntax of both the functions.

fun.call(object, arg1, arg2, ....);

fun.apply(object, [argsArray]);

 

Hope you have enjoyed this post.

In subsequent post we will look at how to avoid this edge cases by using various well known pattern and practices.

Categories: JavaScript Tags:

JavaScript Scope

March 23, 2012 Leave a comment

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers.

Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily)

Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service.

Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code.

public void Main () {
    int a = 5;
    if (true) {
        int b = 10;
    }
    // This will throw compile time error as b is not defined
    // and not within the scope of function Main();
    Console.WriteLine(b);
}

If you write the same code in JavaScript, then the value of ‘b’ will be available outside the ‘if’ block. The reason for this is JavaScript does not have block level scope. Scopes works at the function level and because of a feature called ‘hoisting’ all variable declaration in JavaScript is moved to the top of the function.

You can read more about hoisting here http://rajeshpillai.tekacademy.com/hoisting/

function scopeDemo() {
    var a = 5;
    if (true) {
        var b = 10;
    }
    // This will work even though 'b' is defined inside if block because of 'hoisting'
    alert(b);
}

scopeDemo();  // Invoke the function

Remember, Scope in JavaScript is at function level and not block level.

So, contrary to popular guidelines of most programming lanaguage to declare variables as late as possible, in JavaScript it is recommended to declare all your variables as early as possible.
Happy Scoping !!!
Categories: JavaScript Tags: ,

Hoisting

March 22, 2012 2 comments

Hoisting is one of the feature in JavaScript that puzzles many beginners and intermediate developers.  Hoisting is a feature wherein all the variables are moved to the outermost scope, which is function, in JavaScript.  This may sometimes result in seemingly strange behavior.

Before and after hoisting

 

The output of the above program is an alert with a value of 10.  Traditional logic would have lead us to believe that the value of alert should be undefined.  But because of hoisting the variable is moved to the top of function declaration.  Its important to realize that only the variable declaration is moved and not the initialization.

Recommendation: Always declare your variables at the top of the function scope.

Similar to variable hoisting we also have function hoisting.  Function hoisting has different behaviors based on the fact if the function is an expression or a declaration.

A function is an expression if it is assigned to a variable.  The assignment may also hold an anonymous or named function.   A function declaration is fully hoisted whereas a function expression has the hoisting behaviour of the variables as seen above.

Checkout the jsfiddle demo for a running application.
http://jsfiddle.net/rajeshpillai/e6eLv/1/embedded/
Watch out for next post where we will be demystifying “scope” in JavaScript.

Categories: JavaScript Tags:

JavaScript for Web and Library Developers

March 22, 2012 Leave a comment

This is my first blog post on my home domain and in this series of posts I will explore various facets of JavaScript language that will help us become better programmers.  The idea is tear apart the language and understand how to use the features and build libraries like jquery, knockoutjs, backbonejs.

The idea is not to replicate this libraries, but understand the inner workings using better JavaScript coding practices, design principles and thereby make the web a better place to visit..

We will be covering the following topics, though not in order and there may be addition to this list.

  • Foundations
  • Patterns
  • Closure
  • this keyword
  • Hoisting
  • Anonymous function
  • Currying
  • Server side JavaScript
  • Canvas
  • etc.

Hope you will enjoy this journey with me!

Learn like a child

November 1, 2010 Leave a comment

This is a post to symbolize how much your child can teach you. This is dedicated to all the teachers in our little ones who periodically reminds us or open up little nuggets on the philosophy of living and learning.

Have you ever paid attention to how a child learns? For e.g. if you give him anything for e.g. a toy, what does he do with it?

First since toys are usually bright in colors kids are attracted to it. Once toys catches their attention the child touches it. Then it shakes it to hear the sound. Then it smells it. Then it try to put it in his mouth. And finally it throws it away…..

Hmm.. You may think this is silly and the child’s attention span is very less. But in reality the child is using all the five senses to understand things around it. For e.g. he sees the colour, he touches it, he smells it, he shakes it to hear the sound, he puts it in his mouth to check how it tastes and then when there is nothing more to learn he throws it and tries to break it to see how things are made!

Essentially this is the learning process with which each one of us is born with but we tend to break this natural habits. We do this in many ways? For e.g. when kids come to us say to play or ask anything normally we divert them to some other activities like a television, or a toy or anything. What we don’t realize is in the process we are curbing their natural instinct to learn and explore things around them.

For kids learning is everything, even learning is more important than playing so much as playing is more important that eating and so much as eating is more important than sleeping. Kids try to learn in every possible way. And as adult we do the exact opposite. Next time when kids ask us anything or breaks things, don’t discourage them as this is the way they learn.

Time for some reflection now!!!

Personal Development : Time, Planning , Repairs & Maintenance

These are just my thoughts, but some you may find something interesting in it. Please think over it. We may know many things, but still we always keeps procrastinating it. I have written this as I have heard many people coming back and saying they don’t have time to do things they like. These are my thoughts buy may be useful to someone else too.

Certain things in life needs periodic repairs and maintenance. To cite some examples , your CAR, your HOUSE, your personal laptop/desktop, your health etc.

Likewise there are certain other things in professional life that requires repair/ maintenance /or some kind of polishing, so that you always stay on top of it. But they are not always obvious. Some of them are

- Improving your communication skills
- Increasing your vocabulary
- Upgrading your technical skills
- Pursuing your hobby
- Increasing your knowledge/awareness etc… etc…

And then there are certain things that we are always short of…. one is TIME.

We all know TIME is one of the most precious things in life and yet we all are very miserable at managing it. Remember you can only manage it and not control it. You can only control which you own or which you create. In theory time is infinite. So, there should be abundant of it. But remember one thing, you know this, it’s not reversible. Once it has elapsed you cannot live it again. Think over it.

So, how do find that golden 25th hour every day.

To find the 25th hour you need to reflect back on your current daily activities. Analyze them and see where you are spending most of your time and is it really important. Even the 8 hours that you spent in the office, is it spent fruitfully. At the end of the day is the 8 precious hour that you spent was worth it. Just reflect back on your activities. Did you learn something? If yes did you make a point to NOTE IT. If you didn’t NOTED it then was the time you spent really worth it. Just ponder over it.

Some calculations of your daily activities where most of the time is spent. Let’s start (in no particular order though)

- Sleep (6.5 hours) [Remember you only require 6 good hours of sleep every day]. Some may thing it is 8, but it’s a myth.
o To achive 6 hours of sleep and be in good health you can practice 15 minutes of daily meditation. So effectively you can round it to 6.5 hours.
- Morning chores(2 hours) : Some may need to prepare breakfast and all other things.
- Office commuting (avg. to and fro 3 hours)
- Office Work (avg 9.5 hours)

Total Hours: 21 hours effective time which is spent irrespective of what you do. There may be some variations here and there.

Still you have 3 hours EXTRA. Where do these 3 hours go?

If you can find it, then you may get that golden 25th hour out of these 3 hours. Let’s discount 2 hours for contingencies, still you have 1 hour with you.

If you can’t find it then you are living a direction less life.

As you can see, the 25th Hour lies within the 24 hours of the day. It’s upto each one of us to find and make use of it.

Now what can you do with that 25th hour i.e. 1 hour extra of your life. Imagine the possibility.

Again some calculations

1 hour daily * 30 days = 30 hours every month
30 hours pm * 12 month = 360 hours every year.

360 hours every year seems very promising. Let’s add some contingencies, say, let’s be optimistic and say 50 % contingency.

Still you have 180 hours every year. That leaves with 30 minutes every day of extra time. That’s hell a lot of time, if you could manage it.

These may sound like a high talk [yes, it is, unless you apply these simple rules and rationalize your everyday living and stop procrastinating].

NOTE: I haven’t taken weekend, holidays and leaves into account. So, that leaves us with a lot of buffer time. You can meet family friends, relatives, other tasks, and yet have these 180 pure hours of joy every year. Do whatever you want to do with it.

So, how important is this 180 hours per year to you? Just think over it. You may use it the way you like

- 50 hours [pursue your hobby like drawing, crafting, learn dance, learn juggling, learn swimming, travelling hmm.. anything you like doing and you didn’t had time to do it.]
- 30 hours you can learn a new programming language or technology (i.e. you can get comfortable with it)
- 50 hours [improve existing skills]
- 20 hours [improve you communication skill]. Do some light reading.
- 30 hours [YOU DECIDE WHAT TO DO]?

So, if you had done this for one year you would have learnt a new programming language, upgraded existing skills, improved you communication etc..

If you had done this for two years.. imagine the level of personal development or growth which you may have attained…..

If you had done this for three years….. NOW I think I don’t need to mention this…

So, you still have TIME, as they say TIME is infinite. So, make judicious use of this precious thing. And never ever comeback saying “I don’t have time”. So, if you are RICH in TIME, everything else will be automatically taken care of, as those things may just be a byproduct of how you spend your time…

So, happy TIMING your TIME everyday.

ASP.NET MVC Portal

Get to know all about ASP.NET MVC at
http://aspdotnetmvc.com/

Enjoy….

Categories: asp.net mvc
Follow

Get every new post delivered to your Inbox.