Photograph of a photographic lightroom lightbulb

In a previous article I introduced objects, one of the basic building blocks of JavaScript. In the introductory context of the article, objects were simply table-like containers of data; useful, but not terribly functional. methods are a special form of property that allow us to gain work from objects

Let’s create an object called cat in a piece of JavaScript:

var cat = new Object();
cat.name = "Princess";
cat.furColor = "black";
cat.species = "Siamese";
cat.eyeColor = "blue";

So far that’s a standard array of object properties and values. Let’s add a method at the end of the script, and call on it:

cat.happy = function() { 
	console.log(this.name + " purrs"); 
}
cat.happy();

Save the script on a page: it could be only thing in the document. Then load the page into the browser and look at the result in the console:

“Princess purrs”

methods are simply functions that are part of an object. They can be referenced like any other property, but can contain a great deal of complexity: far more than the basic key-value pairs that we looked at in the first article.

We can create derivations of the object that contain the same methods and functionality, with different data: cat2, for example, might be related to the original cat, and have the same happy method, but a different name… and thus, a different result when we call on cat2.happy.

You can look at the methods associated with any object by using console.dir. Let’s take another example by looking at the methods contained in the console itself – which is, like most everything else, is an object:

console.dir(console);

The entire list of properties and methods for the console object is rather long, and may appear collapsed by default: click to open the list. Similarly, the properties and methods for our cat object:

console.dir(cat);

And for JavaScript’s understanding and manipulation of date and time:

console.dir(Date);

You’ll find some particularly interesting information under prototype in the console when it comes to Date. I’ll talk more about JavaScript prototypes, constructors, and the Date object in future articles.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.