Organizing the Code
All this new functionality will add a lot more complexity to our app, so this is a good time to establish some kind of organization within our code (a much better option than leaving everything in the global scope). After all, we're building a fully functional AJAX application, so we'll want to have it organized properly.
We'll use object-oriented design principles to organize our app. And we'll start, of course, with the creation of a base class for our application -- the Monitor class.
Typically, we'd create a class in JavaScript like this:
function Monitor() {
this.firstProperty = 'foo';
this.secondProperty = true;
this.firstMethod = function() {
// Do some stuff here
};
}
This is a nice, normal constructor function, and we could easily use it to create a Monitor class (or a bunch of them if we wanted to).
Loss of Scope with setTimeout
Unfortunately, things will not be quite so easy in the case of our application. We're going to use a lot of calls to setTimeout (as well as setInterval) in our app, so the normal method of creating JavaScript classes may prove troublesome for our Monitor class.
The setTimeout function is really handy for delaying the execution of a piece of code, but it has a serious drawback: it runs that code in an execution context that's different from that of the object. (We talked a little bit about this problem, called loss of scope, in the last chapter.)
This is a problem because the object keyword this has a new meaning in the new execution context. So, when you use it within your class, it suffers from a sudden bout of amnesia -- it has no idea what it is!
This may be a bit difficult to understand; let's walk through a quick demonstration so you can actually see this annoyance in action. You might remember the ScopeTest class we looked at in the last chapter. To start with, it was a simple class with one property and one method:
function ScopeTest() {
this.message = "Greetings from ScopeTest!";
this.doTest = function() {
alert(this.message);
};
}
var test = new ScopeTest();
test.doTest();
The result of this code is the predictable JavaScript alert box with the text "Greetings from ScopeTest!"
Let's change the doTest method so that it uses setTimeout to display the message in one second's time.
function ScopeTest() {
this.message = "Greetings from ScopeTest!";
this.doTest = function() {
var onTimeout = function() {
alert(this.message);
};
setTimeout(onTimeout, 1000);
};
}
var test = new ScopeTest();
test.doTest();
Share and Enjoy: