Category Archives: JavaScript

Inheritance in JavaScript

In the last post, we saw how to implement class-like objects in JavaScript, despite the language’s lack of actual class data types. The solution used closure to create private fields, which can be either data or functions. Once you’ve got classes up and running, it’s natural to ask if it’s possible to simulate some of the other OOP concepts in JavaScript. Probably the most important of these is inheritance.

After poking about a lot and failing to find a convincing implementation of inheritance, I chanced upon a rather concise post by Steffen Rusitschka. He offers two ways of implementing inheritance, but although his code is fairly easy to use, he really doesn’t explain how it works, and that’s far from obvious. I’ll try to provide a bit of an explanation here.

I’ll look only at the closure-based version, since it follows on nicely from my last post.

At the heart of the technique is this helper code:

(function(){
  CClass = function(){};
  CClass.create = function(myConstructor) {
    var k = this;
    c = function() {
      this._super = k;
      var pubs = myConstructor.apply(this, arguments), self = this;
      for (key in pubs) (function(fn, sfn) {
        self[key] = typeof fn != "function" || typeof sfn != "function" ? fn :
          function() { this._super = sfn; return fn.apply(this, arguments); };
      })(pubs[key], self[key]);
    };
    c.prototype = new this;
    c.prototype.constructor = c;
    c.extend = this.extend || this.create;
    return c;
  };
})();

To use this code, we must first create the data types and then create objects from them. As a test, we will use these data types:

var X = CClass.create(function () {
  return {
    x: 3,

    test: function () { return 2 * this.x; }
  };
});

var Y = X.extend(function () {
  return {
    y: 4,

    test: function () { return this._super() + this.x + this.y; }
  };
});

var xx = new X;
var yy = new Y;

The X class (we’ll call them classes even though JavaScript doesn’t have classes as such; it’s easier to write about that way) has a single data field and a simple function which returns twice the data field. The Y class inherits X, adds a second data field, and overrides the test() function. Note that Y’s test() calls a function called _super(), which calls the base class version of test(). (It’s called ‘_super’ rather than ‘super’, since ‘super’ is a reserved word in JavaScript, even though it doesn’t do anything (yet).)

Once we’ve created the two classes, we can create objects from them in the usual way, using the ‘new’ operator. Let’s try to trace through this code to see what it’s doing.

First, note that the helper code at the top is actually run (notice the parentheses on line 18 at the bottom, which cause the preceding function to be run). Thus we create CClass as an empty function on line 2, and then define the create() function in the remaining code.

Now we look at the declaration of the X class. This is done by calling CClass.create() with the given function as the argument, so this function becomes myConstructor in the helper code. Since CClass is calling create(), ‘this’ refers to CClass, which is an empty function. This is saved in the variable k.

Now a function named c is defined. We’ll look at what it does in a minute, but note that at the end, its prototype is defined as ‘new this’, so the prototype gets a copy of CClass; also the constructor is set to the function c itself. On line 15, an extend() function is defined as either ‘this.extend’ if it’s defined or, if not, ‘this.create’. On the first call to create(), extend() won’t be pre-defined, so on this pass, extend is set to create and becomes the same function as create().

Also, note that the variables k and myConstructor as used inside the c function so, by closure, the values they had when the function was created are saved and are available to the c function when it is used later on.

The result of defining the X class is then to assign to X the c function produced by CClass.create(). Before we move on to Y, let’s see what happens when we create a new object using X, as we do on line 35.

This code treats X like a constructor, so the c function we just created gets called, and its ‘this’ is the object being created. Looking back at the first code block, we see that on line 6, this new object has its _super() defined as k, which you recall was set as the CClass earlier, and which is still available because of closure. Thus here, _super() becomes the empty function CClass.

On line 7, myConstructor() is called using JavaScript’s built-in apply() method, which specifies the calling object as the first argument (which is ‘this’ here) and then passes any arguments as an array (this will be empty in our simple example here). Remember that myConstructor contains the function defined on lines 19 to 25, so the result of this is that pubs contains a new object defined using that function.

Also on line 7, a ‘self’ variable is declared, and set to ‘this’. Since we haven’t actually created any data fields in our new object yet, ‘self’ at present is empty. The idea is to copy the fields from pubs to self so that the object created by constructor call (which is not pubs, since that was created by calling a different function) has the same fields as pubs.

The for loop on line 7 does this. It loops over each key in the pubs object. The body of the loop is another of those self-calling functions. Looking at line 11, we see that the arguments passed to the function are pubs[key] and self[key]. Since self is empty, all these elements will be undefined at this point. This means that the condition on line 9 ‘typeof sfn != “function”‘ will be true for every key, with the result that self[key] gets ‘fn’ assigned to it for every key. Since fn is the first function argument, this effectively runs self[key] = pubs[key], and copies pubs into self as required.

Thus the c function is a sort of roundabout way of implementing a constructor. However, the fun starts when we implement inheritance. On line 27, we create a Y class that inherits X by calling X.extend(). As before, the argument to extend() is a function which acts as a constructor for Y. When we created X, remember that extend() got assigned to create(), so calling X.extend() really calls X.create(). The process is similar to before, except that ‘this’ on line 4 now refers to X rather than CClass. The c function assigned to Y contains the same code as that assigned to X, but the values of k and myConstructor are those in force when X.extend() was called, using closure.

The main differences happen on lines 13 to 15. The prototype is defined as ‘new this’, which means it gets a copy of X. Remember that the prototype of a constructor is what’s the __proto__ of an object created from that constructor points to, so new objects created from this constructor will have all the fields of X.

On line 15, this.extend does exist now so it gets assigned to c.extend.

Now let’s see what happens if we create a Y object, as on line 36. The ‘new’ operator creates a new object by first pointing this object’s __proto__ at the constructor’s prototype. Remember we set Y’s prototype to an X object, so this means that the new Y object yy will inherit the fields of X right at the start. That is, ‘this’ will effectively b an X object at the start of the construction process, so ‘self’ gets assigned to an X object on line 7.

How about pubs, also on line 7? It is initialized by calling myConstructor, which contains the function on lines 27 to 33. This code knows nothing about X, so pubs contains only those fields specified in the Y constructor. Here, we have 2 fields: y and an override of test().

The for loop on line 8 runs for these 2 fields (but not for x, since that’s not mentioned in the Y constructor). For the y field, self[‘y’] is undefined, so it gets assigned to pubs[‘y’] and gets the value 4. However, when we look at the ‘test’ key, self[‘test’] does exist since there was a test() defined in X. In this case both conditions on line 9 are false (both fn and sfn are functions) so self[key] gets assigned to the function on line 10. Because of closure, the values of sfn and fn are saved when this is done.

The result of this is that, when Y’s version of test() is called, this._super gets set to the saved value of sfn, which is X’s version of test(), and then fn (which is Y’s version of test()) gets called via the apply() method. That is, whenever a method in the derived class is called, the corresponding base class method (if any) is available through this._super(). This means, of course, that the function referred to by this._super() varies, depending on which function calls it.

In my experience over years of ‘normal’ OOP using Java and C#, I have used a super() method only a handful of times, so you probably won’t need to use it that much. However, this clever solution makes it available in JavaScript if you need it.

Closure and classes in JavaScript

Although JavaScript is often touted as a class-free language, something very close to classes can be simulated using JavaScript’s support for closure. We’ve looked at C#’s support for closure, but closure is actually even easier to implement in JavaScript.

Suppose we wanted to create a number of bank account objects. One way of doing this is to use a constructor function as we’ve done earlier. We might write something like this:

function OpenAccount(number, balance) {
  this.number = number;
  this.balance = balance;
}

OpenAccount.prototype.deposit = function (money) {
  this.balance += money;
  return this.balance;
}

OpenAccount.prototype.withdraw = function (cash) {
  this.balance -= cash;
  return this.balance;
}

var acct1 = new OpenAccount(1, 1000);

This allows us to create a new account as we’ve done on the last line, where we create an account with number 1 and initial balance of 1000.

While this works, and we can call the deposit and withdraw functions to change the balance, it’s also possible to change the balance directly by writing acct1.balance += 200, which gives us an extra £200 without bothering to use the deposit function. We can do this because the object fields balance and number are public.

In classical OOP, good design says that all data fields should be private, and we should be able to interact with them only by means of interface methods. It looks as though we can’t do this in JavaScript, since there is no ‘private’ keyword (and in fact, no ‘class’ keyword). However, we can do something that amounts to much the same thing using the idea of closure.

Suppose we define the following function:

function account(number, balance) {
  return {
    getNumber: function () {
      return number;
    },

    getBalance: function () {
      return balance;
    },

    deposit: function (money) {
      balance += money;
      return balance;
    },

    withdraw: function (cash) {
      balance -= cash;
      return balance;
    }
  }
}

This function accepts two arguments, just as OpenAccount did, but instead of initializing an object with these values, all it does is return an object containing 4 functions. If you’re used to the classical scoping rules of a language like C#, you might also think this code won’t work. Why? Because we incorporate the function’s parameters ‘balance’ and ‘number’ into the object that is returned. JavaScript’s scoping rules are the same as those of C# and Java, in that function arguments exist only as long as the function is running.

However, because JavaScript implements closure, any function created inside another function gets a copy of the outer function’s internal variables, and this copy exists even after the outer function’s life is over. That’s what closure is; the inner function ‘closes over’ the variables it receives from the outer function and gives these internal copies a separate life of their own.

The key point is that these copies of ‘balance’ and ‘number’ are not data fields of the object returned by the account() function, so there is no direct access to them from the outside. The only way they can be read or written is by means of one of the 4 functions provided. They have, essentially, become private data fields.

To get a feel for how this works, open up a browser (such as Chrome) that supports a console and copy the definition of account() into it. Now try creating an account using this function. Note that since account() returns an object, it’s not a constructor, so you don’t use the ‘new’ operator to create objects. You write simply

var acct1 = account(42, 1000);

First, you can check that the 4 functions work as expected. Try viewing the balance by typing acct1.getBalance(), depositing some money by typing acct1.deposit(500) and so on. You should see that the returned values are what you expect in each case.

Now try accessing the balance directly, without using one of the 4 functions, by typing acct1.balance. You’ll get ‘undefined’ as a result, because the balance isn’t directly accessible.

So where, exactly, are these two data fields ‘number’ and ‘balance’ being stored? To find out, examine the structure of acct1 by typing just acct1 into the console. You’ll see that it’s an Object, so open the Object and look at its insides.

You should see entries for the 4 functions and also the ubiquitous __proto__ object we’ve discussed earlier, but there’s no sign of ‘balance’ or ‘number’.

Open up one of the function entries, say the deposit() function. One of its constituents is <function scope>. Open that, and you’ll see an entry called Closure. Open that, and lo and behold, inside the Closure are our two data fields. So they are being stored after all; they’re just not visible to the outside world, which is just what we want for a proper class.

Those of you who have been following these posts might now notice a possible loophole in all this though. Since JavaScript allows us to add data fields to any object at any time, why can’t we just add a ‘balance’ field to acct1? Let’s try it… Type in acct1.balance = 5000 in an attempt to give our account a free £5000. If you now type just acct1.balance into the console, you’ll get 5000 back as a response, so it seems to have worked.

However, if you type acct1.getBalance(), you’ll find that you still have only the £1000 you started with, and you’ll also find that trying to increase your savings using acct1.deposit() will affect only the original £1000, ignoring the £5000 you tried to add fraudulently.

You can see what’s happened by examining the structure of acct1 in the console again. The new balance field has been added at the top level, but if you dig down into the Closure section of the functions, you’ll find that the original balance is still there, untouched, and it’s that balance that the functions are using.

So as long as your code relies on the interface methods to interact with the data, the acct1 object is secure. That means that if you’ve written your code using this method, any external attempt to hack into it by overriding the private data fields won’t work. Even trying to hack into the object by writing your own function won’t work. If you wrote a function like acct1.fiddle = function(cash) { this.balance += cash; } you’ll find that the fiddle function affects only the top-level balance and not the one in the closure. Leaving off the ‘this’ from ‘this.balance’ doesn’t work either, since there is no ‘balance’ object defined in the scope of the fiddle function.

Functions and methods in JavaScript

JavaScript allows the creation of global functions, as in the simple example

function multiply(x, y) {
  return x * y;
}

This function can be called from anywhere using syntax such as var product = multiply(4, 5) which assigns the value 20 to product.

However, all functions are also objects and, as such, a function can be attached to another object as a data field. Functions that are fields of other objects are usually called methods.

Suppose we define  an object like this:

var number = { value: 0 }

This creates a single object called number which has a single data field called value. We can attach a method to number either as part of its definition, as in this attempt to define a method that squares number’s value:

var number = {
  value: 0,
  square: function() {
    return value * value;
  }
}

number.value = 42;
number.square();

If we run this code (try it in Chrome’s console), you probably won’t get the result you’re expecting. The call to number.square() returns NaN (not a number) rather than the expected value of 42 * 42 = 1764. What went wrong? Analogous code in a language like C# or Java would work, since we’re (kind of) treating number like a class with a data field and a method, and as we know, a class’s methods all have access to the class’s data fields.

JavaScript, as you’ve probably guessed, doesn’t work quite that way. If we refer to an unadorned variable like value, it is assumed that this is a global variable, so the square() method above looks for a global value and, not finding it, returns the indeterminate result of NaN.

You can test this by defining a global value variable and giving it a distinctive value, as in var value = 12; If you now run the line number.square() you’ll get the result 144, so it’s clear where the square() method is getting its ‘value’ from.

To solve this problem, we need to realize that any method gets a ‘bonus’ parameter passed to it, which is the object that calls the function. This object is referred to inside the function by the keyword this, which you’re probably familiar with from C# or Java. However, although using this as a prefix in C# is optional, in JavaScript it’s compulsory if you want to refer to the object calling the method. Thus our revised definition of number looks like this:

var number = {
  value: 0,
  square: function() {
    return this.value * this.value;
  }
}

number.value = 42;
number.square();

Now if we run the last 2 lines again, we get the expected result of 1764.

In fact, global functions are also passed a this parameter, except this time it refers to the global object, and use of this here actually is optional. For example, we could define the global function

function doubleValue() {
  return 2 * this.value;
}
doubleValue();

Running this code gives the result 24, since this.value now refers to the global value. We could equally well have defined this function as

function doubleValue() {
  return 2 * value;
}
doubleValue();

We’d get the same result.

This behaviour makes sense for truly global functions, but we run into problems if we declare functions inside methods. A rather contrived example is a revised version of the square function above. Suppose we define a new method for number called newSquare:

number.newSquare = function () {
  var innerSquare = function () {
    return multiply(this.value, this.value);
  }
  return innerSquare();
}

number.newSquare();

If number.value is still 42 and the global value is 12, running this code produces the value 144. Now what’s wrong? Even though we’ve included the this prefix when referring to value, the global value is still being used instead of number.value.

The problem here is what is widely regarded as a mistake in the design of JavaScript. Whenever a function that is not a field of an object (that is, a method) is called, this is always bound to the global object. The function innerSquare is a utility function declared within a method, but is not a method itself, so its this is the global object, not the number object that calls newSquare.

This sort of code design is very common, so there is a standard workaround to avoid this problem. Inner functions such as innerSquare do have access to local variables inside their container method, so we can define a local variable (usually called that) and assign it to point to this. We can then use that whenever we want to access the object that called the method. We therefore rewrite newSquare as follows:

number.newSquare = function () {
  var that = this;
  var innerSquare = function () {
     return multiply(that.value, that.value);
  }
  return innerSquare();
}

number.newSquare();

This time we get the correct result of 1764.

Prototypes in JavaScript

JavaScript’s prototype system is often confusing for programmers coming to the language from an object-oriented background, as with C# or Java. Here I’ll try to dispel a bit of confusion by looking at how object prototypes work.

For what follows, it’s very useful if you enter the code into a console (such as can be found in the Google Chrome browser) and experiment with the various commands.

We can create an object by writing its fields literally, as in

var comic = {
  title: 'Spider-man',
  issue: 343
}

Type this into the console and then examine the comic object (by just typing ‘comic’ (without the quotes) on a line by itself and hitting return). Its type is given as Object, which isn’t surprising. Open up this node, and you’ll see that in addition to the two fields ‘issue’ and ‘title’, there is a third field called (in Chrome, though this won’t be true in all browsers) __proto__, whose type is given as Object. If you expand __proto__, you’ll see a list of fields that include the functions that are defined for all objects, such as toString, hasOwnProperty and so on.

The __proto__ object is the prototype that is attached to all objects by default. In its expansion, you may notice that it does not have its own __proto__ field. This is because the prototype of Object is the end of the prototype chain (more on this later). Thus it is more correct to say that all objects except Object’s prototype have their own prototype.

So what use is this prototype? Its importance arises from the fact that you can customize it by adding fields to it, or replacing it completely with an object of your own making.

We saw in the post on creating objects with a constructor that we can add methods to objects by adding a method to the constructor’s prototype. Let’s have a closer look at what’s going on here.

First, we need to make one thing clear. It is true that all objects (including functions) have the prototype we’ve been referring to by the name __proto__. However, functions (and only functions) also have a separate ‘prototype’ property, where in this case, the word ‘prototype’ is spelled out in full and not abbreviated or enclosed in underscores. Please understand that __proto__ and ‘prototype’ are not the same; only __proto__ is the true prototype of an object or a function. So what’s the ‘prototype’ property of a function used for?

When we use the ‘new’ operator to create a new object from a constructor, the new operator creates the new object and then links the object’s __proto__ to the constructor’s ‘prototype’. Note that this is a reference link from the object to the constructor, and not a copy of the constructor’s prototype to the object’s __proto__. This means that any changes to the constructor’s prototype are reflected in the __proto__ of all objects created from it. More on this below.

For example, suppose we define the Book constructor as in the previous post (we’ve made a slight change in that the name of the constructor has been moved to the function definition rather than being a separate var, but the effect is the same):

function Book(author, title, price) {
  this.author = author;
  this.title = title;
  this.price = price;
};

var book1 = new Book("Asimov", "Foundation", 3.55);

Now examine ‘book1’ in the console. You’ll find that it contains the three data fields defined in the constructor and also __proto__. Expand __proto__, and you’ll see that it contains the constructor, along with another __proto__, the latter of which is the base Object prototype. If you expand the constructor, you’ll see that it contains its own __proto__ and also a ‘prototype’ of type Book. It’s this ‘prototype’ that is used to create new objects.

If we add a method to the constructor’s ‘prototype’ like this:

Book.prototype.description = function () {
  return this.author + ': <i>' + this.title + '</i>  £' + this.price;
}

we can examine the __proto__ of ‘book1’ again. Now we’ll find that the ‘description’ function has been added:

> book1
  Book
    author: "Asimov"
    price: 3.55
    title: "Foundation"
    __proto__: Object
      constructor: function (author, title, price) {
      description: function () {
      __proto__: Object

If we expand ‘description’, we find that it, too, has a __proto__ and a ‘prototype’, since it’s a function. However, its ‘prototype’ isn’t used for anything, since ‘description’ isn’t a constructor.

A neat trick is to use prototypes to create a new object that inherits its prototype from an existing object. To do this, we can add a new method to Object (so that it’s available to all our code). This is the ‘beget’ method, and is due to Douglas Crockford:

if (typeof Object.beget !== 'function') {
  Object.beget = function (copy) {
    var F = function () { };
    F.prototype = copy;
    return new F();
  };
}

var book3 = Object.beget(book1);

The initial ‘if’ checks if ‘beget’ has already been defined (if it hasn’t, the typeof will return ‘undefined’). We then define Object.beget as a function which takes a single argument copy. Inside beget(), we create an empty function called F, and assign this function’s ‘prototype’ (not __proto__) to be the object copy that we want to copy. F is treated as a constructor, and the ‘new’ operator is used to create a new object from F, which is then returned. Recall that using ‘new’ creates a new object whose __proto__ is a copy of the constructor’s ‘prototype’, so the effect is to generate a new object whose __proto__ is copy.

The book3 object inherits all the fields of book1 and is shown as being of type F. Expanding F, we find that its only field is __proto__, which is of type Book, and if we expand that, we get the same fields as we had for book1.

If we now access book3.title, we’ll get ‘Spider-man’ which of course was copied from book1. What’s important to note, though, is that the ‘title’ field isn’t in the top layer of fields for book3; it’s one layer down, in the Book prototype. This illustrates that JavaScript will look for a field iteratively from the top down, so if it doesn’t find the field you want at the top layer, it will look at the next layer, and then the next, and so on, until it either finds the field or hits the Object.__proto__ at the bottom. If it doesn’t find it there, it will return ‘undefined’.

The prototype chain includes only the __proto__ fields; the ‘prototype’ properties have nothing to do with this process. They are used only in the creation of new objects in a constructor.

What happens if we try altering the data fields in these objects? For example, suppose we try writing book3.author = ‘Simak’. We find that the ‘author’ field of book3 is indeed now Simak, but has this assignment affected anything on the prototype chain? We can examine book3’s structure once again to find out.

We find that, rather than altering the ‘author’ field in the Book __proto__, book3 has a new author field at the top level. That is, we now have

> book3
 F
  author: "Simak"
  __proto__: Book
    author: "Asimov"
    price: 3.55
    title: "Foundation"
    __proto__: Book

Assigning a new value to an existing field in a __proto__ doesn’t overwrite the existing value; it adds a new value at the layer above the __proto__.  JavaScript ‘knows’ which author to use, since when we request the author field, it starts at the top in its search, so the first author found will be Simak. If we remove that field with the statement delete book3.author, we find that the top layer author is removed, and the author property reverts to that stored in the __proto__, so it becomes ‘Asimov’ again.

What happens if we do change a property in the __proto__? Suppose we start with book1 and book3 as above (without the episode where we introduced ‘Simak’), so both books have ‘Asimov’ as their author. We now try writing book3.__proto__.author = “Delaney”. Now we find that the authors of both book1 and book3 have changed to Delaney, since we changed the underlying __proto__ on which both these books are defined. (By the way, fiddling with __proto__ directly isn’t terribly good programming practice, not least because not all browsers support it. We did it here just to illustrate a point.)

We can modify a constructor’s ‘prototype’ after the constructor has been used to create objects and these modifications will be available to the existing objects. This is because the __proto__ in an object is a pointer back to the constructor’s prototype that was used to create it. For example, we could add a method to Book by writing Book.prototype.getPrice = function() { return this.price; }. Having done that, we can now write book1.getPrice() to retrieve book1’s price of 3.55.

[Beware of a gotcha here, though. Since __proto__ is a reference to the constructor’s ‘prototype’, if you redefine the constructor’s prototype to point to a totally new object, the __proto__ reference won’t follow this change; it will still point to the old object. That is, it’s OK to modify fields and methods of the ‘prototype’ object originally associated with the constructor, but it’s not OK to replace that ‘prototype’ object.]

jQuery: creating new tags

We’ve seen that we can select existing elements on a web page in many ways using the $(selectorsyntax, where ‘selector’ can take on any of the many forms we’ve seen in earlier posts. The $() syntax can also be used to create new HTML which can then be inserted into your document.

To do this, simply put the desired HTML (enclosed in quotes) directly as the argument. Thus $(‘<input type=text/>’) creates a new text input box.

Merely creating a new object does not, however, insert it into the document. To do that, you need to use a method such as appendTo(). Thus  $(‘<input type=text/>’).appendTo(‘body’) will add the text box to the end of the body, so that it appears at the bottom of the page.

The easiest way of trying this feature out is to load a page (such as the one we’ve been using for examples up to now) that uses jQuery into a browser such as Chrome that has a console, and then typing some commands into the console. The results should be instantly visible on the page.

That’s about all there is to say about the single-argument method of creating HTML. There is, though, another version, in which a second argument can be passed. This second argument allows attributes to be specified.

It’s true that we could just include all the attributes in the raw HTML in the first argument, but it’s sometimes cleaner and easier to read if we can lay out the attributes more explicitly.

For example, we could create a new text input as follows:

$('<input />',
  {
    type: 'text',
    title: 'A test text box',
    click: function () {
      alert($(this).attr('title'));
    },
    css: {
      backgroundColor: 'peachpuff',
      border: '2px dotted red'
    }
  }).appendTo('body');

We’ve moved the ‘type’ attribute to the second argument, and added a ‘title’ (which is displayed as a tooltip when the mouse hovers over the text box). We’ve also added an event handler for a mouse click, which just displays an alert box containing the title. (It’s probably more conventional to add the event handler using a method, but putting it in the attribute list is perfectly valid.)

We’ve also added a couple of style properties in the css attribute. The css attribute is a bit odd in that it gets translated to a ‘style’ attribute in the HTML, and some of the attribute names get changed. For example, the css ‘backgroundColor’ is changed to ‘background-color’ in the style. You can, if you like, specify the ‘style’ attribute explicitly in the jQuery, but you’ll have to use the style names instead of the css names, and put the whole set of styles into a single string. The above example would be written:

$('<input />',
  {
    type: 'text',
    title: 'A test text box',
    click: function () {
      alert($(this).attr('title'));
    },
    style: 
      'background-color: peachpuff; border: 2px dotted red' 
 }).appendTo('body');

jQuery: special selectors

We’ve seen how to select document elements based on their tags, ids, classes and attributes. jQuery also provides a number of specialized selectors and filters.

We’ll use the same HTML code as before for our examples. Here it is:

<body>
  <h2>jQuery Selectors</h2>
  <table>
    <tr>
      <th colspan="2">Comic Summary</th>
    </tr>
    <tr class="headerRow">
      <th id="comicHeader" class="header cell">Comic</th>
      <th id="numberHeader" class="header cell">Number</th>
    </tr>
    <tr>
      <td class="cell">Thor</td>
      <td class="cell">34</td>
    </tr>
    <tr>
      <td class="cell">Superman</td>
      <td class="cell">158</td>
    </tr>
    <tr>
      <td colspan="2">
        Which is best?<br />
        <label> <input type="radio" name="dcMarvel" /> DC</label>
        <label> <input type="radio" name="dcMarvel" /> Marvel</label>
      </td>
    </tr>
    <tr>
      <td colspan="2">
      What are your favourites?
        <ul>
          <li><label><input type="checkbox" />Batman</label></li>
          <li><label><input type="checkbox" />Superboy</label></li>
          <li><label><input type="checkbox" />Fantastic Four</label></li>
          <li><input type="checkbox" />Iron Man</li>
          <li><input type="checkbox" />Incredible Hulk</li>
          <li><input type="checkbox" />Green Lantern</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="text" id="jqtest" /></td>
    </tr>
  </table>
</body>

Selecting by position

There are several ways of selecting elements based on their position in a list. The filters :first and :last (all filters begin with a colon (:)) select the first and last elements in the selected context, respectively. For example, if we wrote $(‘li:first’) we would select the first li element on the page (which is the Batman checkbox). Similarly, $(‘li:last’) selects Green Lantern.

The :first and :last filters ignore the depth of nesting of elements and just pick out the absolute first and last matching elements. Thus $(‘label:first’) gives the DC radio button and $(‘label:last’) gives the Fantastic Four checkbox.

If we omit a selector before the filter, jQuery uses the entire page as the context. Thus $(‘:first’) selects the <html> tag which encloses the whole page, and $(‘:last’) selects the text input tag at the bottom.

The :first-child filter selects the first element in the context that is a child of another element. $(‘label:first-child’) gives the first three labels in the checkbox list because each of these labels is the first child of a li tag. Note that it does not include the DC radio button since, although this button is the first label child of the td tag, it’s not the first child: the br tag has that honour. If we delete the br tag, then the DC button is included; the text ‘Which is best?’ within the td does not count as a child since it just part of the td tag.

As you might expect, $(‘label:last-child’) selects labels that are last children of another node. In this case we get the first three checkbox labels (since they are the only children, they are both first and last children) and the Marvel radio button.

$(‘label:only-child’) selects labels that are the sole child of another node; here that means the first three checkbox labels.

There are also filters :even and :odd which select even and odd elements from the context, using a zero-based index. Thus $(‘li:even’) selects Batman, Fantastic Four and Incredible Hulk and $(‘li:odd’) selects Superboy, Iron Man and Green Lantern.

We have :eq(n), :gt(n), and :lt(n) for finding elements that are at index location n, or greater than or less than n. Again, n is zero-based. Thus $(‘li:gt(2)’) selects Fantastic Four, Incredible Hulk and Green Lantern.

Finally, there is the :nth-child(n) selector, which is a bit unusual, in that its index argument starts at 1 rather than 0. (This is for compatibility with CSS, but if you’re working with jQuery it can be a bit of a pain, since all the other index-based selectors start with a 0 index.) $(‘li:nth-child(2)’) gives Superboy.

There are a couple of other versions of :nth-child(). One takes an argument of ‘even’ or ‘odd’ which returns the even or odd elements in the list, except of course because the list now starts with 1, these give complementary results to using just ‘even’ or ‘odd’ on their own. That is $(‘li:nth-child(odd)’)  gives the same result as $(‘li:even’) and vice versa.

The final form of :nth-child() takes a simple formula as its argument. We can write :nth-child(Xn+Y where  and Y are integers. This will return every Xth element, starting with element Y. Thus $(‘li:nth-child(3n+2)’) returns every 3rd element starting with element 2, giving Superboy and Incredible Hulk.

Custom filters

There are quite a few filters that do their selection based on the type or state of element you’re interested in. Filters that select specific types of element are :button, :checkbox, :file (equivalent to ‘input [type=file]’), :header (selects <h1>…<h6>), :image (same as ‘input [type=image]’), :input (any form input element), :password, :radio, :submit (same as ‘input [type=submit]’), :reset and :text (same as ‘input [type=text]’). These should all be fairly self-explanatory, but give them a try using the HTML above and the header block given earlier, and use the Console in Chrome or Firefox to see what you get.

Somewhat more interesting are the filters that act on the state of an element. The :checked filter selects radio buttons or checkboxes that are checked.

This seems a good place to introduce the tricky :not() filter. As you can guess, it returns the inverse of whatever selector is passed to it as its argument, but you have to be a bit careful. For example, you might think that since :checked gives all radio buttons and checkboxes that checked, :not(:checked) should give you all radio buttons and checkboxes that are not checked. In fact, what it does give you is all elements that are not checked, which means every element on the page (including non-radio buttons and non-checkboxes) except radio buttons and checkboxes that are checked.

If you want just the non-checked checkboxes, you can write $(‘:checkbox:not(:checked)’), since that restricts the context to just checkboxes before applying the :not filter. If for some reason you actually do want both unchecked radio buttons and checkboxes, you can write $(‘:radio:not(:checked), :checkbox:not(:checked)’) being careful not to leave out the comma in the middle.

The :contains() filter can also trap you. Its argument is some text, and it returns all elements that contain that text. The trap lies in the fact that if any element within the context is an ancestor of the element that contains the text, that element also gets included in the results. For example, if we wrote $(‘:contains(best)’), then the td element containing this text would be selected, but so would the html, body, table, tbody and tr elements that are that td’s ancestors. To get just the td element, we would have to write $(‘td:contains(best)’).

If we want to select tag types that have another tag type as their ancestor, we have already seen that we write, for example $(‘tr li’) to find li elements that are children of tr elements. The :has() filter can do the inverse; it finds elements that have a particular type of element as a descendent.

$(‘tr:has(li)’) returns the tr element containing the checkbox list. Again, note that the child element can be at any depth below the parent.

The remaining filters are all fairly obvious. They are :disabled, :enabled, :hidden, :visible, :selected and :parent. The :parent filter returns elements that are parents, not the parents of elements. If you want to find the parents of a set of elements, you need to use the parent() function rather than a filter. Thus $(‘li’).parent() finds the ul element that is the parent of all the li tags.

jQuery selections: id, class and attributes

In the last post, we saw how to select page elements by searching for tag names. Sometimes, we’d like to select elements based on other criteria. There are several ways of labelling or marking tags.

For the purposes of an example, we’ll modify the body of the page given in the previous post, so it now becomes:

<body>
  <h2>jQuery Selectors</h2>
  <table>
    <tr>
      <th colspan="2">Comic Summary</th>
    </tr>
    <tr class="headerRow">
      <th id="comicHeader" class="header cell">Comic</th>
      <th id="numberHeader" class="header cell">Number</th>
    </tr>
    <tr>
      <td class="cell">Thor</td>
      <td class="cell">34</td>
    </tr>
    <tr>
      <td class="cell">Superman</td>
      <td class="cell">158</td>
    </tr>
    <tr>
      <td colspan="2">
        Which is best?<br />
        <label> <input type="radio" name="dcMarvel" /> DC</label>
        <label> <input type="radio" name="dcMarvel" /> Marvel</label>
      </td>
    </tr>
    <tr>
      <td colspan="2">
      What are your favourites?
        <ul>
          <li><label><input type="checkbox" />Batman</label></li>
          <li><label><input type="checkbox" />Superboy</label></li>
          <li><label><input type="checkbox" />Fantastic Four</label></li>
          <li><input type="checkbox" />Iron Man</li>
          <li><input type="checkbox" />Incredible Hulk</li>
          <li><input type="checkbox" />Green Lantern</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="text" id="jqtest" /></td>
    </tr>
  </table>
</body>

First, a tag may be given an id attribute. The HTML standard specifies that no two visible page elements may have the same id. The key word here is ‘visible’; you can define several page elements with the same id, so long as only one of them (or none of them) is visible at any given time. In the example above, we’d added an id to each of the th tags in the table.

Secondly, most page elements can be assigned a class to which they belong. The name ‘class’ is a bit misleading if you’re familiar with object oriented programming, since an HTML class doesn’t have many of the properties of a true OOP class. In HTML, a class is really little more than a label which can be used to identify groups of tags on a page. In the above HTML, we’ve assigned all the td elements to have the class ‘cell’. Unlike the id, the class of a tag need not be unique; in fact, it usually won’t be, since the idea is normally to identify a set of tags that have a common property.

A tag can belong to more than one class. In the above code, the th tags are members of both the ‘header’ and ‘cell’ classes. To define multiple classes, we list the class names separated by whitespace. Both the id and class can be any valid string.

Finally, many tags have various attributes. Although these attributes are usually used to specify some properties of the tag, they can also be used as identification. Actually, both the id and the class are attributes, but there are many others for some tags. In the above example, the first th tag has a ‘colspan’ attribute, and the radio and checkbox input tags have ‘type’ attributes (the radio buttons also have a ‘name’ attribute).

One of the most common uses of these ways of labelling tags is in specifying CSS rules, but we can also use them in jQuery selectors to pick out groups of elements on which we can act. Using the above page as an example (you can use the same head as the last section if you want to try this a live browser), we can see a few examples.

Searching using the id

To use an id, prefix the the id name with a #. For example, the expression $(‘#comicHeader’) will find the th tag with that id. Note that although ids must be unique amongst visible elements, it is possible that some currently hidden tags may have the same id, and this expression will find all tags that have that id, so you may need to filter the results to be sure of getting the one you want.

If you want to restrict the search to tags of a certain name, simply prefix the id name with the tag name. Thus $(‘th#comicHeader’) will find all th tags with an id of comicHeader (which happens to give the same result as the earlier example in this case).

It’s important to note that there is no whitespace between the th and the #. If you did put a blank between them, you would then be searching for descendents of a th node that had that id, which in this case would return an empty list. If you tried $(‘tr #comicHeader’), though, you’d then get the comicHeader node again, since it’s in a node which is a descendent of a tr node.

You can search for several ids by separating them with commas. Thus $(‘#comicHeader, #numberHeader’) finds both th nodes with ids.

Searching using the class

Using the class as a search term is pretty much the same as using the id except you prefix the class name with a period (.) instead of #. Thus $(‘.cell’) finds all tags with a class of ‘cell’.

Somewhat counter-intuitively, although you can define a tag that belongs to two classes by listing the class names separated by whitespace, if you try finding all tags that belong to both of two classes in the same way, you are doomed to fail. For example, the query $(‘.header .cell’) returns an empty list. What this query is really asking for is a list of elements with a class of ‘cell’ that are descendents of a tag with class ‘header’. Thus if we tried $(‘.headerRow .cell’) we’d then get the two th tags with a class of ‘cell’.

If you do want a list of tags that belong to both of two different classes, you have to leave out the whitespace. Thus $(‘header.cell’) will give you the two th tags again.

You can combine ids and classes in the same search. Thus $(‘#comicHeader.header.cell’) looks for tags that have an id of comicHeader and classes of both ‘header’ and ‘cell’.

Searching using attributes

Finally, you can use any attribute as a search term. The syntax for this encloses the attribute and its value in square brackets. For example, to find all checkboxes, we can use $([type=checkbox]). We’ve left the quotes off ‘checkbox’, but in fact it doesn’t seem to matter whether you use them or not; thus $([type=”checkbox”]) also works.

You can also search for tags that merely have a given attribute, regardless of what value that attribute has. For example, we can get a list of all tags that have ids by writing $([id]). The notation above for searching on id or class isn’t quite just a shorthand for using the id and class attributes though. The class has its own logic that allows things like multiple class definitions and searches, as we saw above. If we tried something like $([class=header]) we’d get an empty result. The attribute search attempts to match the exact string to the attribute, and there is no tag with just ‘header’ as its class, so the search fails.

jQuery: simple selections

Although JavaScript is very handy for client-side manipulation of web pages, it suffers from at least two serious drawbacks. First, it can take a lot of code to do relatively simple things (like finding a particular element within a web page). Second, different browsers (particularly Internet Explorer) often require different code to do the same thing, so writing a web page that will always behave the same in every browser can be a major headache.

jQuery solves many of these problems. It is a JavaScript API which defines a large number of functions that both reduces the amount of code needed and eliminates many of the cross-browser problems.

At the core of jQuery (as you might guess from its name) is its ability to search the web document in a myriad of ways. (It can, of course, do a lot of other things, but more on that later.) We’ll have a look at some of these search techniques here.

First, we need to draw an important distinction between the two ways a jQuery function can return its result. Most functions return a wrapped set, which is a set of page elements contained within a JavaScript data structure. It’s a set, since there are no duplicated elements within it, even if the search string could match the same element in more than one way. Some jQuery functions will return bare elements, but we won’t be concerned with any of those in this post.

Second, most jQuery functions are called from a wrapped set, do something to that set, and then return another wrapped set. Sometimes, the second set is the same as the first one (although with some modifications to its elements), but sometimes (as with a filter) the second set is a different set than the original, as it may contain different, or more or fewer, elements. Again, we won’t be worried about this much here, since we’re going to consider mostly just a single function that searches the page for specific elements. What we do with those elements is the subject of future posts.

The format for a query in jQuery is $(<query string>), where <query string> is a string that tells the function what to look for. If you know how to use cascading style sheets (CSS), you’ll be happy to hear that most of the CSS selector strings also apply in jQuery selectors. (If you’re not familiar with CSS, as I have to admit I wasn’t when I started looking at jQuery, then this is all new, but never mind.)

In order to try out some jQuery selectors, we need a page for it to work on. Here’s the body of a web page that has a few basic tags in it:

<body>
  <h2>jQuery Selectors</h2>
  <table>
    <tr>
      <th colspan="2">Comic Summary</th>
    </tr>
    <tr>
      <th>Comic</th>
      <th>Number</th>
    </tr>
    <tr>
      <td>Thor</td>
      <td>34</td>
    </tr>
    <tr>
      <td>Superman</td>
      <td>158</td>
    </tr>
    <tr>
      <td colspan="2">
        Which is best?<br />
        <label> <input type="radio" name="dcMarvel" /> DC</label>
        <label> <input type="radio" name="dcMarvel" /> Marvel</label>
      </td>
    </tr>
    <tr>
      <td colspan="2">
      What are your favourites?
        <ul>
          <li><label><input type="checkbox" />Batman</label></li>
          <li><label><input type="checkbox" />Superboy</label></li>
          <li><label><input type="checkbox" />Fantastic Four</label></li>
          <li><input type="checkbox" />Iron Man</li>
          <li><input type="checkbox" />Incredible Hulk</li>
          <li><input type="checkbox" />Green Lantern</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="text" id="jqtest" /></td>
    </tr>
  </table>
</body>

This produces the following page:

For reference, this page has the simple style (specified in a CSS file):

body {
  background-color:lightgray;
  font-family:Arial;
}

Now, suppose we want to select all <li> tags. In this case, the jQuery call is simply $(‘li’). If you want test this out, you can create your own HTML file and put the above body into it, then add the following head section (before the body, of course):

<head>
  <title></title>
  <link href="Content/jQueryDemo.css" rel="stylesheet" />
  <script src="Scripts/jquery-1.8.2.js"></script>
  <script>
    $(function () {
      $('#jqtest').keypress(
        function (event) {
          if (event.keyCode === 13) {
            $('*').css({
              backgroundColor: 'lightgray',
              border: 'none'
            });
            console.log($($(this).val()));
            $($(this).val()).css({
              backgroundColor: 'palegreen',
              border: '1pt solid darkgreen'
            });
          }
        });
    });
  </script>
</head>

This assumes that you’ve got your CSS file in Content/jQueryDemo.css and that the jquery library is in Scripts/jquery-1.8.2.js. If you have a different version of jQuery or put your files in different places, you’ll need to modify those 2 lines in the header. If you’re using Visual Studio,  you can include jQuery as described in the last post.

As for the script in the header, don’t worry about it for now. Just be assured that when you type a query string into the text box and hit return, those page elements that you’ve selected will be highlighted in green.

Also, if you’re running a browser (such as Google Chrome) that has a console, you’ll see the selected elements printed out in the console. To activate Chrome’s console, right click on the page and select ‘Inspect element’, then click the Console tab. This is well worth doing, since not all of the selected elements get highlighted, and it’s reassuring to see that these elements have in fact been selected.

If you’ve got this page running, try typing li into the text box and hitting return. You should see this:

 

The 6 li elements have been highlighted. The reason that the top 3 don’t have their text highlighted is that these checkboxes are defined using the <label> tag, while the bottom 3 have a bare checkbox with some text after it. The label is a separate element that sits on top of the list, so it doesn’t get selected. Try typing label into the box and you’ll see just the top 3 checkboxes lit up, along with the 2 radio buttons.

If you want to select both li and label elements, enter li, label. That is, a comma separated list will select all elements that match any term in the list.

Although this is fairly simple, the results are global, in that you’re selecting all tags in the entire page. Suppose you wanted to select only those inputs that are inside labels. This time, you can type in label input (without a comma). (In this case, the display won’t show any items lit up, presumably because the label overwrites the input that it contains, but if you look in the console, you’ll see that the two radio buttons and top 3 checkboxes are selected.)

This form of list first selects the left-most tags (labels here) then selects children of those tags that satisfy the second condition. We could string together more tags if we have a deeper nesting on the page. Note that the input doesn’t have to be the immediate child of the label; if a label contains an input as its descendant at any point it will be selected.

If you want to restrict your choice to only immediate children, you can write td > label. This selects label tags that are immediate children of td tags. This will give you the 2 radio buttons, but not the top 3 checkboxes, since they are buried inside a ul and li tag. To compare, try typing td label (without the >) and this time you’ll get the top 3 checkboxes as well.

That’s about enough for a first post.

 

JSON with ASP.NET MVC 4

As a newcomer to JavaScript and jQuery, I wanted to write a (supposedly) simple little web site which used JSON (JavaScript Object Notation) to transmit information from a database to a web page. Surprisingly there didn’t seem to be any self-contained example or tutorial (that I could find) that showed how to do this basic operation. So here is the result of my attempt. It turns out that it is actually quite simple, once you know what to do.

First off, what is JSON? It is an alternative to XML as a way of sending information from one device to another. It’s a subset of the notation that can be used in JavaScript to define an object literal, which we saw in the last post. As an example, we might have some information on the numbers of various titles of comic books that are stored in a database. After we’ve retrieved this data from the database, we can encode it into JSON, so that it looks like this:

[
  {"Title":"Batman","Count":1},
  {"Title":"Fantastic Four","Count":2},
  {"Title":"Spider-man","Count":2},
  {"Title":"Superman","Count":1},
  {"Title":"Thor","Count":2}
]

That is, the data are stored as name-value pairs. In this case, each element in the array is actually a compound object consisting of two name-value pairs (Title and Count). We could have a simple list of single name-value pairs, or we could have deeper nesting of objects. There are various restrictions on the syntax for JSON objects, but as we’ll see, in MVC 4 you won’t usually have to write your own JSON, since there is a library routine that does it for you.

Now that we know what JSON is, how do we use it as a mediator between a database and a web page in ASP.NET MVC 4? We’ve seen that the procedure for generating web pages in MVC is as follows.

  1. Write a controller that contains a method that is called when a client requests a web page from the server.
  2. Write a view that is linked to the controller method, and which generates the markup that is returned to the client.

The controller method will usually collect some data from some other source, such as a database or some other C# code (which is usually part of the Model in MVC). This data is then packaged up, possibly in a C# object, and sent to the View, where the View formats the data and generates the HTML which is interpreted by the browser.

The procedure for using JSON doesn’t quite fit this pattern. Basically what happens is this:

  1. Client requests a web page.
  2. Controller method is called to process this request.
  3. The corresponding View is returned to the browser.
  4. The View contains some JavaScript code that makes another request to the server, this time asking for some data in JSON format.
  5. different Controller method from that called in step 2 is called to generate the JSON, which is returned to the browser.
  6. The JavaScript code processes the JSON and generates some HTML which is displayed.

The key point is that the JSON is not meant to be displayed as raw data by the browser; rather, it is retrieved by the browser and then processed on the client side before it is displayed.

We’ll illustrate this by showing how the data above can be obtained from the database and sent to a web page using JSON. First, we’ll add a controller to our ComicShop project that we’ve been using to demostrate things:

using System.Web.Mvc;
using ComicShop.Models;
using System.Collections.Generic;

namespace ComicShop.Controllers
{
  public class JsonController : Controller
  {
    //
    // GET: /Json/

    public ActionResult Index()
    {
      return View();
    }

    private IComicRepository comicRepository;

    public JsonController()
    {
      comicRepository = new ComicRepository();
    }

    public JsonController(IComicRepository comicRepository)
    {
      this.comicRepository = comicRepository;
    }

    public ViewResult JsonSummary()
    {
      return View();
    }

    public ActionResult Summary()
    {
      IEnumerable<ComicSummary> summaries = comicRepository.GetSummaries();
      return Json(summaries, JsonRequestBehavior.AllowGet);
    }

  }
}

This controller uses the IComicRepository interface and ComicRepository class that we introduced earlier. This controller contains two methods of interest here. The one called JsonSummary() simply returns a View, which is the View that requests the JSON data (we’ll get to this View in a moment).

The Summary() method is the one that produces the JSON data. The first line in this method requests the data from the database (see the earlier post for details of how this is done; all that’s important here is that we do get this data). The data is returned as an IEnumerable<ComicSummary> list. The ComicSummary class is defined as:

namespace ComicShop.Models
{
  public class ComicSummary
  {
    public string Title { get; set; }
    public int Count { get; set; }
  }
}

That is, it contains two data fields named Title and Count.

The second line in Summary() calls the library method Json() to create the JSON data. It is passed the list of ComicSummary objects in the variable summaries. The second parameter allows Summary() to provide JSON data in response to an HTTP Get request (by default, such a response is blocked for security reasons, so this parameter is needed). This returns the JSON string we gave above.

That’s all there is to producing JSON data (as promised, you didn’t have to actually write any raw JSON yourself, since the Json() method does it for you). If you want to verify that Summary() actually works, you can call it directly from a web browser by using the URL http://localhost:36195/Json/Summary (the port number for your localhost server will probably be different; what’s important is the path /Json/Summary), and you should see the raw JSON data printed in the browser.

Note that we did not associate a View with the Summary() controller method. As far as the browser is concerned, it is receiving raw text as a response to its request to Summary, so it just displays that. We need to do something special if we want it to interpret the JSON as data and incorporate it into a ‘real’ web page.

To that end, we turn our attention to the JsonSummary() controller method, and have a look at its View. This is in the file JsonSummary.cshtml:

<h2>JsonSummary</h2>
<script>
    $.getJSON('/Json/Summary',  function (data) {
        var items = [];
        $.each(data, function (key, val) {
            items.push('<li>' + key + ': ' + val.Title + ' (' + val.Count + ')</li>');
        });

        $('<ul/>', {
            html: items.join('')
        }).appendTo('body');
    });
</script>

As you can see, most of this file is JavaScript. However, it’s not all primitive JavaScript; it makes use of jQuery, so you need to make sure your web project has jQuery installed. If you started with an Empty project, you’ll need to do this yourself; if you started with a full Internet project, it will already be included.

To add in jQuery, right-click on the Solution in SolutionExplorer and select Manage NuGet Packages. Search in the Online section and find jQuery, then click Install. JSON should already be installed – you can check this by opening up References in SolutionExplorer and seeing that Newtonsoft.Json  is included in the list.

NuGet should take care of installing these packages and should find some jQuery JavaScript files in your Scripts folder (if you didn’t have a Scripts folder, it will be created by the installation).

We’re not quite done yet, though. In order for jQuery to be used in your View, that View needs to run the jQuery script. You could include a <script> tag in the View file itself, but if you plan on using jQuery in a lot of Views, it makes more sense to put it in the common layout file which we considered earlier. This file is called _Layout.cshtml and is in the Shared folder within the Views folder. Add the call to the jquery script in the <head> section of the layout. The modified _Layout.cshtml file looks like this:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <script src="~/Scripts/jquery-1.8.2.js"></script>
    <meta name="viewport" content="width=device-width" />
    <title>Comics</title>
</head>
<body>
    <h2>Comic Shop</h2>
    <div>
        @RenderBody()
    </div>
</body>
</html>

The call to the script is on line 9. The actual version number of jquery may differ from 1.8.2 if you install it later on, but just insert whatever version you got from NuGet.

That’s all we need to get the JavaScript to run, but there’s one more thing that’s very useful, and that’s to get Intellisense working for jQuery. Complete instructions for doing this are here, provided you’re using VS 2012. My _references.js file looks like this:

/// <reference path="jquery-1.8.2.intellisense.js" />
/// <reference path="jquery-1.8.2.js" />

Right, now we can look (finally) at JsonSummary.cshtml. A lot of the code there relies on a knowledge of JavaScript and jQuery syntax, so I won’t go through it in detail. However, I’ll mention a few key points so you can adapt it for your own purposes.

First, the $.getJSON() call is a jQuery method which makes a request to the URL given as its first argument for some JSON data. In our case, we use a relative URL /Json/Summary (the leading / is important: don’t leave it out!). If this call is successful, the JavaScript function given as the second argument to $.getJSON is called. (If the call fails, this function isn’t called, and you’ll get nothing on your web page apart from the HTML that is outside the <script> tag. This can make debugging a nightmare, since you won’t know what’s wrong, but never mind.)

The argument ‘data’ sent to this function is the JSON code. This function then constructs an array called ‘items’ by iterating through ‘data’ using the jQuery $.each() method. The second argument to $.each() is another function, this time taking two arguments. The ‘key’ argument is the integer index of the element from ‘data’ that is being processed, and ‘val’ is that actual element from ‘data’. Remember from the JSON above that each element in ‘data’ is a compound object of type ComicSummary, so it contains a Title and a Count field. We access these fields to create a HTML list entry on line 6, and push this onto the items array.

The last bit of code on lines 9 to 11 creates a <ul> tag and adds the items list to it, then it adds the <ul> tag to the body of the page. The final result looks like this:

JavaScript objects

After many years as an OO programmer using primarily C++, Java and C#, I’m finally taking a first look at JavaScript. At the lower syntax level, that of most operators, expressions, if statements and loops, JavaScript is much like other OO languages such as C# and Java. Above that level, things diverge quite rapidly. I’ll have a look at how JavaScript handles objects (in the OO sense) here.

One of the big differences between JavaScript and other mainstream OO languages (I’ll use C# as the main point of comparison from here on, as it’s the language I’m using for most other stuff) is that JavaScript is an untyped language. That is, you don’t need to (in fact, you can’t) specify the data type of a variable when it is declared. JavaScript has the ‘var’ keyword which should be used when declaring a variable. (I say ‘should be used’ since it is possible to declare a variable without using ‘var’, but this effectively makes the variable global, which is usually undesirable, so it’s best not to do it.)

However, JavaScript’s var is not the same as C#’s var. In C#, once a variable has been declared using var (or indeed, declared using any method), the data type of that variable is fixed. In the case of C#’s var, the data type is determined by the object to which that variable is initialized. In JavaScript, the data type of a variable is mutable, so you can, for example, declare a variable and assign a string to it, and later assign a different type such as a number. JavaScript is therefore loosely typed.

Another difference is that although objects are used in JavaScript, classes are not. This might seem contradictory; how can you have an object if it’s not an instance of a class? In this sense, JavaScript objects are similar to anonymous types in C#. An object can be created by simply listing some name-value pairs. For example, if we wanted an object that represents a book, we could write:

var bookObj = {
  author: "Delaney",
  title: "Nova",
  price: 5.47
}

This form of object is called an object literal, since it is a literal description of what one particular object contains. We could then use this object in a browser page by writing (assuming that the above code is stored in the file /Scripts/ObjectTest.js relative to the home page):

<h2>Books</h2>
<script src="~/Scripts/ObjectTest.js"></script>
<script>
    document.writeln(bookObj.author + ': <i>' + bookObj.title + '</i>  £' + bookObj.price + "<br>");
</script>

(We could, of course, have put the document.writeln() statement in the file as well, but this way we can see how to use the results of the first script in a script within the browser.)

This method is fine if we’re content to create single objects, but one of the powers of traditional OO languages is the ability to define a new data type (the class) and then create a number of objects of that data type. How do we do that in JavaScript?

It turns out that although JavaScript doesn’t have a class as such, it has a structure that, in practice, is very close to one, at least in the way it can be used. A class can be simulated in JavaScript by using a function.

A JavaScript function is actually an object in the same way that the untyped object above is. That is, a function can be created and passed around the program like any other object. In this sense, JavaScript functions are similar to C# delegates.

All objects in JavaScript have a prototype object behind them. This has a number of implications which we’ll get to in due course, but for now we can think of it as a form of inheritance. Just as all C# classes by default inherit the ‘object’ class, all object literals like the example above are backed by the Object.prototype object.

All functions are backed by Function.prototype, but each individual function also has its own prototype object behind it. This prototype can be used to add methods to a function.

Functions have a wide variety of uses, which we’ll get to in due course, but for now, the one we are interested in is the constructor function. This looks a lot like a class definition in C#. Here’s a constructor for a Book object:

var Book = function (author, title, price) {
  this.author = author;
  this.title = title;
  this.price = price;
};

Book.prototype.description = function () {
  return this.author + ': <i>' + this.title + '</i>  £' + this.price;
}

var book1 = new Book("Asimov", "Foundation", 3.55);
var book2 = new Book("Adams", "Hitchhiker's Guide to the Galaxy", 4.95);

The first 5 lines declare the constructor function, and define three data fields within it. All functions begin with the keyword ‘function’, followed by an argument list (which can be empty). As JavaScript doesn’t impose data types on its variables, this argument list contains no types, just parameter names.

The body of the constructor makes use of the keyword ‘this’. As in C#, ‘this’ refers to the object which called the function, so here, ‘this’ refers to the Book object that is being created. This code should look very similar to a constructor in C#.

Line 7 shows how to add a method to a Book object. We access the hidden prototype of the Book constructor, and then append the method name, which is ‘description’ here. The prototype is allowed to refer to ‘this’ in the same way as the original constructor. Here we just return a string containing some HTML to render the Book’s data in a browser.

The last two lines show how we can use the Book constructor to create a couple of objects. Again, these declarations look very similar to those in C#.

To use this code in a browser, we could put the following in the HTML file for the web page:

<h2>Books</h2>
<script src="~/Scripts/ObjectTest.js"></script>
<script>
    document.writeln(book1.description() + "<br>");
    document.writeln(book2.description() + "<br>");
</script>

Running the script from the file creates the book1 and book2 objects, and we can just call the description() method on them to obtain the HTML to render on the web page.

There are other ways of achieving the same result, but this little example should illustrate how JavaScript handles objects and object creation.