Tag Archives: objects

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):

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

(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:

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

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.