I stole this title from Bear Bibeault and Yehuda Katz’s excellent book jQuery in Action.

At the back of the book was a really good summary of things you need to know about Javascript but might not (another great reference is Javascript: The Good Parts by Douglas Crawford).

To remind myself what these things are I am listing them here:

Reference identifiers

Normally we reference properties using the dot (period) identifier:

var ride= new Ride();
ride.make = ‘Yamaha’;

But you can also reference properties like this:

ride.make
ride[‘make’]
ride[‘m’ + ‘a’ + ‘k’ + ‘e’]

and like this.

var p = ‘make’;
ride[p];

I didn’t know you could do that in Javascript, but sometimes you have to. Especially if you don’t know the name of the property you are looking for, or it has spaces in it like this:

ride['a property name with spaces']

Object literals

Or can create objects using the new operator (like Java and C#) or you can create them with this convenient shorthand:

var ride = { 
	make: ‘Yamaha’,
	year: 2005,
	owner: {
		name: ‘Biker Bob’
	}
};

This is handy for constructing JSON objects for passing data around (which is the way a lot of communication happens over the web these days – not so much XML anymore).

Properties of windows

var someVariable = ‘Some quote’;

and

someObject.aProperty = ‘Some other quote’;

Are basically the same thing. Each instance assigns a string to a variable and an object.

When you define variables at the top level like this (not inside any function), it’s a programmer friendly way of referencing a property of the predefined JavaScript ‘window’ object. Any reference made in the top-level is implicitly made on the window instance.

Functions are first class citizens

Functions get treated just like variables in JavaScript. Meaning you can assign them to variables and pass them around.

var ride = { 
	make: ‘Yamaha’,
	year: 2005,
	owner: { name: ‘Biker Bob’, occupation: ‘Bounty hunter’ },
	whatAmI: function() {
		return this.year + ‘ ‘ + this.make + ‘ ‘ + this.model;
        }
};

Functions as callbacks

Functions are passed just like variables in Javascript. You can define a function and pass it to a method as a callback like this:

function hello() { alert('Hi there!'); }
setTimeout(hello, 5000);

See – just like any other variable. Very powerful. Or you can inline it all at once like this:

setTimeout(function() { function hello() { alert('Hi there!'); }, 5000);

The functions described here at either top-level functions (which we know are top-level windows properties) or assigned to parameters in function calls. You can also assign functions to properties of objects.

What is ‘this’ all about?

In class-based OO languages, the this pointer generally references the instance of the class for which the method has been declared.

In Javascript, where funcations are first-class ogjects that aren’t declared as part of anything, the object referenced by this (termed the function context) is determined not by how the function is declared but by how it’s invoked.

This means the same function can have different contexts depending on how it’s called.

For example (taken from jQuery in action) say we have the following object:

var ride = {
    make: 'Yamaha',
    whatAmI: function() {
        return this.make;
    }
};

And we call it 4 different ways:

var o1 = { handle: 'o1' };
var o2 = { handle: 'o2' };
var o3 = { handle: 'o3' };
window.handle = 'window';

function whoAmI() {
    return this.handle;
}

o1.identifyMe = whoAmI;

alert(whoAmI());                // window
alert(o1.identifyMe());         // o1
alert(whoAmI.call(o2));         // o2
alert(whoAmI.apply(o3));        // o3

The results are the comments beside the call just above.

So you can see that it’s not how an object is declared that determines it’s context, it’s how it is called.

Closures

A closure is a Function instance coupled with the local variables from its environment that are necessary for it’s execution.

It’s a bundle of Function and variables that execute together, and close out together.

When a function is declared, it has the ability to reference any variables that are in it’s scope at the point of declaration. No surprise’s here, typical C#/Java.

But, with closures, these variables are carried along with the function even after that point of declaration has gone out of scope, closing the declaration.

The ability for callback functions to reference the local variables in effect when they were declared is an essential tool for writing effective Javascript.

Here’s an example:

$(function() {
    var local = 1;
    window.setInterval(function() {
        $('display').append('<div>new Date() + 'at local=' + local + '</div>');
        local++;
    }, 3000);
});

<body>
    <div id="display"></div>
</body>

If you were unfamiliar with closures you might see a few problems with the above code.

We might surmise that, because the callback will fire off three seconds after the page is loaded, the value of local is undefined during the execution of the callback. After all, the block in which local is declared goes out of scope when the ready handler exits.

But when you run it it works!

May 6 ... local = 1
May 6 ... local = 2
May 6 ... local = 3

While it is true that the block in which local is declared goes out of scope when the ready handler exists, the closure created by the declaration of the function, which includes local, stays in scope for the lifetime of the function.

Another important feature of closures is that a function context is never included as part of the closure. For example the following code won’t work as we expect:

this.id = 'someID';
$('*').each(function() {
    alert(this.id);
});

Remember that each function invocation has it’s own function context so that, in the preceding code, the function context is an element from the jQuery wrapped set (not the property of the outer function set to ‘someID’.

When access to the object serving as the function context in the outer function is needed (more akin to classic OO), you need to store the outer context by creating a copy of the this reference in a local variable that will be included as part of the closure.

this.id = 'someID';
var outer = this;
$('*').each(function() {
    alert(outer.id);
});

This local variable outer, which is a part of the outer function’s context, becomes a part of the closure and can be access in the callback function.

Closures are indispensable when creating elegant code using jQuery commands that utilize asynchronous callbacks, which is particularly true in Ajax requests and event handling.

For more excellentness on Javascript and jQuery (where these abbreviated examples comes from) pick up a copy of Bear and Yehuda’s book. You won’t be disappointed