Get started with object-oriented JavaScript code

Learn how to create objects using the JavaScript language

The JavaScript language includes several built-in objects, such as Array , String , and Date , to name a few. But, if there are custom functions that you want to create, you can create your own custom objects using one of the available methods. There are a lot of benefits to developing your own custom objects using the JavaScript language, one being that you can easily reuse these custom objects across multiple projects without modification. Additionally, custom objects provide access to functions that are beyond the prebuilt objects the JavaScript language has to offer. When combined with other custom objects, you can use them to build a library that can be distributed to other web developers.

Properties and methods are what make objects functional and usable. The easiest way to understand the concept of an object is to think of any real-life object. For example, use a dog as your object. A dog can have properties such as legs, ears, a tail, possibly a collar, and so on. A dog can have methods such as barking, eating, sleeping, and so on. The methods can alter the properties of the dog. For example, if the dog is barking, its ears may stand up, and if the dog is sleeping its ears might be floppy (unless of course the dog is a Great Dane). Imagine wanting to use a dog object in your project. It can save a lot of time if you are interested in creating multiple dog objects because they all have a lot of the same basic properties and methods. And, if you want to use a dog object in another project, you can easily reuse the object you already created.

Following are the different ways to create a custom object using the JavaScript language:

The Object function

function Literal notation

Object constructor and prototyping

This article covers all three options for creating custom objects using the JavaScript language while demonstrating how to create a simple photo gallery object using each option.

To get started with this article you need a basic understanding of the JavaScript language. Follow the examples by downloading the example code from the Download section. If you want to learn more about the basics of the JavaScript language, visit the articles referenced in Related topics.

The Object function

The Object function is one of the easiest ways to create an object with the JavaScript language. The JavaScript language includes a function named Object , which when used with the new operator creates an object. The Object function is the starting point for any custom functionality you want to achieve by creating an object. To reference an object that has been created using the new operator and Object function, you simply need to assign it a variable name (Listing 1).

Listing 1. Creating a custom object using the Object function

var Gallery = new Object();

To make the Gallery object useful, you can add properties and methods to give it functionality. Listing 2 includes three properties and three methods that have been added to the Gallery object.

Listing 2. A custom Gallery object with properties and methods

var Gallery = new Object(); window.onload= function() { Gallery.Images = ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg']; Gallery.CurrentIndex = 0; Gallery._loopInterval = setInterval(Gallery.Next, 2500); }; Gallery.Next = function() { if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { Gallery.CurrentIndex++; } else { Gallery.CurrentIndex = 0; } Gallery.Display(); }; Gallery.Prev = function() { if(Gallery.CurrentIndex > 0) { Gallery.CurrentIndex--; } else { Gallery.CurrentIndex = (Gallery.Images.length-1); } Gallery.Display(); }; Gallery.Display = function() { var photoGallery = document.getElementById('photo-gallery'); var currentImage = Gallery.Images[Gallery.CurrentIndex]; photoGallery.src = "../assets/img/"+currentImage; };

The number in the property You can modify the number in the _loopInterval property to increase or decrease the time between each image.

The properties of the Gallery object are CurrentIndex , Images , and _loopInterval . To define them as properties of the Gallery object, you simply assign them to the Gallery object using dot syntax—append a dot and a variable name and then assign that variable a value. The methods used in Listing 2 are Next , Prev , and Display . To define them as methods of the Gallery object, you use dot syntax and assign each one its own function.

Both the Next and Prev methods use the properties in this object. The CurrentIndex property identifies what the current index of the Images array is so that when you increase or decrease the index it references a different array item. The Images property is an array that stores the images that you are displaying in the gallery. The _loopInterval property automatically loops through the images in the gallery every 2.5 seconds.

HTML sample used throughout the article The HTML file in Listing 4 is the one that you use throughout the other examples in this article. The Gallery object is the only thing that changes based on the creation type of object you use.

The Next and Prev methods in the Gallery object are similar—the former increases the current index in the Images array and the latter decreases it, which results in a different photo being displayed each time the Display method is called.

To call one of the methods in this object, such as the Next method, you simply need to reference the Gallery object, followed by a dot, followed by the name of the method ( Next ), and, finally, followed by opening and closing parentheses (Listing 3).

Listing 3. Calling the Next method in the custom Gallery object

Gallery.Next();

To actually put this object into action, you can easily create controls that navigate the images in your Images array. First, you need to include the JavaScript file, which in this case is an external file named Gallery.js. Then you just need to add an HTML img tag that displays the images and add hyperlinks that control the next and previous navigation (Listing 4).

Listing 4. Sample HTML file with the custom Gallery object and Gallery functions

<html> <head> <title>Getting Started with Object-Oriented JavaScript</title> <script type="text/javascript" src="js/Gallery.js"></script> </head> <body> <img src="../assets/img/istockphoto_14149033.jpg" id="photo-gallery" /> <p> <a href="#" onclick="Gallery.Prev();">< Previous</a> <a href="#" onclick="Gallery.Next();">Next ></a> </p> </body> </html>

Literal notation

Another way to create objects with the JavaScript language is through literal notation, which is supported by JavaScript 1.2 and above. Literal notation can contain properties and methods just like objects created with the Object function.

Creating custom JavaScript objects with literal notation is similar to creating an associative array in other programming languages. To create an object using literal notation, you simply need to assign a variable to opening and closing curly brackets, as shown in Listing 5.

Listing 5. Creating a custom object using literal notation

var Gallery = {};

To define properties in an object created with literal notation, you need to use a colon between the variable name and value and separate all properties with commas, as shown in Listing 6.

Listing 6. Adding properties to a custom object using literal notation

var Gallery = { Images: ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg'], CurrentIndex: 0 };

Defining methods in an object created with literal notation is similar to the way you define properties. You create a method by stating the variable name followed by a colon and then the function. If you define multiple methods in the object, you need to separate them with commas (Listing 7).

Listing 7. Adding methods to a custom object using literal notation

var Gallery = { Images: ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg'], CurrentIndex: 0, Next: function() { if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { Gallery.CurrentIndex++; } else { Gallery.CurrentIndex = 0; } Gallery.Display(); } };

Another difference between using the Object function and literal notation is that you don't have to define properties and methods using the object name before each one. Listing 8 shows the complete example of the Gallery object using literal notation.

Listing 8. A custom Gallery object using literal notation

var Gallery = { Images: ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg'], CurrentIndex: 0, Next: function() { if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { Gallery.CurrentIndex++; } else { Gallery.CurrentIndex = 0; } Gallery.Display(); }, Prev: function() { if(Gallery.CurrentIndex > 0) { Gallery.CurrentIndex--; } else { Gallery.CurrentIndex = (Gallery.Images.length-1); } Gallery.Display(); }, Display: function() { var photoGallery = document.getElementById('photo-gallery'); var currentImage = Gallery.Images[Gallery.CurrentIndex]; photoGallery.src = "../assets/img/"+ currentImage; } }; window.onload = function() { var _loopInterval = setInterval(Gallery.Next, 2500); };

To use this object, you can include it in the HTML file that you used in Listing 4. The rest of the code, including the function calls, remains the same.

The only drawback to objects that use the Object function or literal notation is that you cannot instantiate them multiple times. For example, you can only use the new operator with these two object types the initial time that the object is created, meaning that you cannot reuse the object to create another instance. For the example in this article, if you want to create multiple galleries in a single HTML file, you need to include the JavaScript file multiple times and give the gallery a different name each time, which results in a lot of duplicate objects with different names. Therefore, these object types are not good for those situations. On the other hand, if you only need to use an object one time, these object types work fine. To create an object that you can instantiate multiple times, you need to use the object constructor and prototyping.

Object constructor and prototyping

When you need an object that you can instantiate multiple times, the object constructor and prototyping are the answer. An object constructor is just like any other function, but when naming the function you actually give the function the name of the object in which you are creating it. In this case, that object name is Gallery . However, because you want to have the ability to create multiple instances of the gallery object, I named it GalleryObj for this example.

The object constructor begins to differentiate itself when you start adding properties and methods to it. I personally don't add methods to my constructors because it is arguably bad form, but it is possible to do so. When adding a property or method to an object constructor, you use this keyword before the property or method names to assign them to the object itself (Listing 9).

Listing 9. Defining properties in an object constructor

function GalleryObj() { this.Images = ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg']; this.CurrentIndex = 0; this._loopInterval = setInterval(this.Next, 2500); }

Rather than adding methods to the object constructor, I prefer to use the prototype keyword. The prototype keyword provides the ability to create inheritance in the JavaScript language. For example, when you want an object to inherit a method after it is defined using the object constructor, you use the prototype keyword. The prototype keyword essentially lets you attach a method to an object and then allows all instances of that object to use that method (Listing 10).

Listing 10. Adding methods to an object using the prototype keyword

GalleryObj.prototype.Next = function() { if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { Gallery.CurrentIndex++; } else { Gallery.CurrentIndex = 0; } Gallery.Display(); };

In Listing 11, you can see the full example of the Gallery object using the constructor function and prototyping.

Listing 11. A custom GalleryObj object using object constructor and prototyping

function GalleryObj() { this.Images = ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg']; this.CurrentIndex = 0; this._loopInterval = setInterval(this.Next, 2500); } GalleryObj.prototype.Next = function() { if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { Gallery.CurrentIndex++; } else { Gallery.CurrentIndex = 0; } Gallery.Display(); }; GalleryObj.prototype.Prev = function() { if(Gallery.CurrentIndex > 0) { Gallery.CurrentIndex--; } else { Gallery.CurrentIndex = (Gallery.Images.length-1); } Gallery.Display(); }; GalleryObj.prototype.Display = function() { var photoGallery = document.getElementById('photo-gallery'); var currentImage = Gallery.Images[Gallery.CurrentIndex]; photoGallery.src = "../assets/img/"+ currentImage; }; var Gallery = new GalleryObj();

For the sake of using the same HTML file, I named the object GalleryObj so that when you instantiate it you can give the instance the name Gallery . The other difference is that the interval for auto-advancing the gallery photos is now defined per instance rather than within the object definition. This lets you control the interval for each gallery instance separately.

Now if you are interested in creating another instance of the GalleryObj object, you can simply define a new one, as shown in Listing 12.

Listing 12. Creating another instance of the custom GalleryObj object

var Gallery2 = new GalleryObj();

As you can see, the object constructor is quite powerful in that it lets you create unlimited instances of an object. Prototyping is also powerful because it lets you add methods on the fly, which then become accessible to all instances of that object.

Prototyping core JavaScript objects

Now that you understand prototyping, you can take a look at adding custom methods to core JavaScript objects. Sometimes you need additional functionality but not necessarily a custom object. For example, imagine that you need to get the index of a particular item in your gallery's Images array. Rather than writing a random non-reusable function to do this, you can extend the Array object by using the prototype keyword to add a new method to the object (Listing 13).

Listing 13. Using the prototype keyword to add a method to the core Array object in the JavaScript language

Array.prototype.GetIndex = function(item) { for(var i=0; i<this.length; i++) { if(this[i] == item) { return i; } } }

To use the new method that you added to the Array object, you can simply call it like any other function call from any array you create. Listing 14 contains an Images array called GetIndex that gets the index of a particular image in the array.

Listing 14. Using the prototype keyword to add a method to the core Array object

<html> <head> <title>Getting Started with Object-Oriented JavaScript</title> <script type="text/javascript" src="js/Array.js"></script> <script type="text/javascript"> var Images = ['istockphoto_14149033.jpg', 'istockphoto_14232771.jpg', 'istockphoto_14667148.jpg']; var index = Images.GetIndex('istockphoto_14232771.jpg'); alert("Index: "+ index); </script> </head> <body> </body> </html>

Extending core objects in the JavaScript language lets you add functionality to objects that already exist. It's pretty amazing when you think that you can literally tell the Array object to do more and then be able to reuse that extended functionality in any of your projects.

Conclusion

Each of the options covered in this article are valid in their own way. The Object function and literal notation are similar, and the choice of which one to use is really based on the preference of the developer. Both are good options for objects that do not need to be instantiated multiple times. When looking to create an object that needs to be instantiated multiple times, the object constructor and prototyping option is ideal.

Creating custom objects in the JavaScript language gives you the ability to create far more complex functionality while keeping your code simple and organized. I hope this article has inspired you to use custom objects in your JavaScript projects to create complex interactivity with a purpose.

Downloadable resources

Related topics