Javascript Objects 101

Javascript Objects for Beginners

Javascript has a lot of overlooked potential as an object-oriented language, but it deserves a closer look. Today, we’ll be looking at literals, prototyping to extend existing objects, and last creating our own Javascript class. Get ready for some client-side, object-oriented fun!

Even though Javascript is object-oriented, a lot of people don’t take full advantage of the powerful solutions objects can give you. And it’s easy to see why – it can be daunting at first to hear all these terms like prototyping and closures and literals. In fact, though, with a good explanation it’s not that hard, and since objects are the very building blocks of JS, it’s important for any web coder to have a grasp of how they work. Let’s start in the best place – the beginning!

Basic Objects

Javascript has several built in objects – Date(), Array(), Math(), String(), etc., and of course you can’t really write Javascript without using the DOM, so you’re probably more familiar with objects than you know. In order to start using an object, you have to create an instance of it. Object instances are created with the new operator:

var dateObject = new Date(); //the variable ‘dateObject’ is now a new Date() object
var arrayObject = new Array(); //the variable ‘arrayObject’ is now a new Array() object
//etc.

After you’ve done this, you can use the properties (variables that are part of the object) and methods (functions that are part of the object) and put them to use in your code. If this is still a stretch for you, I recommend reading this excellent article on the basics of object-oriented Javascript, or you’ll always free to ask a question in the comments!

Object Literals

Literals are like the to-go version of objects. These little guys are especially handy for passing multiple arguments to a function – you’ll see them used in jQuery a lot. Literals don’t need a class/constructor, they’re just free-wheeling collections of data. Here’s what they look like:

var objectLiteral = {
property1 : “some value”,
property2: “some other value”,
functionX : function(){
//do stuff here
}
}

And you’ve just created an object literal – congratulations! Properties and methods are defined inside the curly brackets with the “:” assignment operator. They can then be referred to just like any other property or method via:

var x = objectLiteral.property1; //accesses the value of property1
objectLiteral.functionX(); //calls functionX

As I said, this makes passing multiple arguments tons easier. You’ve probably seen jQuery’s animate() method before, which is an excellent example:

$(function(){
$(“.some-class”).animate({ //literal starting right here
opacity : “0.5”,
background : “#000000”,
width : “200px”
});
});

This allows us to pass as many methods as necessary, and inside the animate function (or whatever function you’re working on) you can just set one argument and refer to it:

function animate(args){
document.write(args.opacity); //outputs “0.5”, same thing with background and width
// Of course, this is nothing like the real jQuery.animate(), this was just an example to show
//how it works on the other end
}

Alright, so that’s all real basic stuff, but I wanted to make sure you understand that before I go on to the next part – extending existing objects.

Prototyping

Not to be confused with the PrototypeJS library, prototyping is the add-on mechanism of Javascript –enabling you to extend existing objects as you see fit. The freedom that this gives us to create custom methods and properties is quite exciting. Prototype is actually its own object , and can be referenced through all other objects, so:

Date.prototype.example = “Lorem ipsum“; //adds a property to the Date() object
//”example” is now present in all instances of the Date() object:
var newDate = new Date();
alert(newDate.example); //will alert “Lorem ipsum” – the value of example

What’s a practical use for this? Well, let’s say you wanted to add an array_unique() property to the array object, similar to PHP’s. Prototype gives you the ability to do that (this snippet is modified from one written by Chris Heilmann) :

Array.prototype.unique = function(){
if(this.length && typeof this!==’string’){
var sorter = {}, out = [];
for(var i=0,j=this.length;i<j;i++){
if(!sorter[this[i]+typeof this[i]]){
out.push(this[i]);
sorter[this[i]+typeof this[i]]=true;
}
}
}
return out || this;
}

Prototyping is great, but sometimes you need to start from scratch and create your own brand-new object. We looked at object literals as the quick, easy way to do this, but if you’re going to be doing heavy-duty development, it’s time to call a class in.

Classes

A class, sometimes referred to as a constructor in Javascript, is the template for an object. You can take one class and make as many objects out of it as you want, which will all have the same characteristics. Classes allow us to do a lot of robust scripting efficiently and without excess code.

Unfortunately, Javascript is not a fully mature object-oriented language, so there is no class operator. Instead classes are simply defined as functions, and methods/properties are attached to them via ‘this’, like so:

function exampleClass(){ //define like a normal function
//methods and properties can now be defined using ‘this’:
this.property1 = “some value”;
this.method1 = function(){
alert(this.property1);
};
}

exampleClass()” can now be initiated and used just like the built-in Javascript classes:

var exampleObject = new exampleClass();
alert(exampleObject.property1); //OR
exampleObject.method1();

Understanding the Nitty-Gritty

If you spend time reading about Javascript Objects, you’ll undoubtedly hear terms like ‘inheritance’, ‘scope’, ‘closures’, and others. If you don’t have a background in object-oriented programming, it’s easy to be left wondering, “What does all this mean?” Although these are fairly complex topics, I don’t want to leave you in the dark on this stuff, so we’ll take a quick whirlwind tour, and then I’ll give you some resources that will help you find out more if you want to:

Inheritance

Inheritance is the way that an object can inherit the properties/methods of another object. In Javascript, this is accomplished by prototyping the parent object right on to the child:

var exampleObj = function(){};
exampleObj.prototype = new Date();

And exampleObj now has all the properties and methods of Date(). Inheritance is very useful for reducing unnecessary repetition of code.

Scope

Scope is, very simply, the accessibility of a variable, or in other words the measure of where it can be accessed. A lot of times in complex programs you’ll have multiple levels of functions and objects going on, so it’s important to understand variable scope. The basic, normal way that scope works is that a variable defined inside a function cannot be accessed outside the function. Sometimes you want to change this, though, which can be accomplished in three different ways – returning the value, making the variable global, or using a closure.

You should be already familiar with returning a value from a function, so I won’t cover that one. As for global variables, they are useful but dangerous. They’re useful because they make your variable accessible everywhere, but dangerous because spreading your variable too far and wide can cause bugs/conflictions later. Because of the inherent dangers in global variables, they should be used sparingly. In case you wondered, they are created by defining a variable without the var keyword. Here’s an illustration of what that looks like:

var test1 = 100; //local variable
var test2 = 200; //local variable
function test(){
var test1 = 1; //local variable
test2 = 2; //this is global, so it accesses the test2 variable outside the function
}
test();
alert(test1); //alerts 100 (stayed the same)
alert(test2); //alerts 2 (has been changed to two)

That leaves us with closures. In short, a closure is usually a function that’s closed inside another function. Because that inner function has access to all its parent’s properties without having to make those properties global, it allows superior organization and scope control. It might look like this:

function someFunction(){
var xyz = “xyz value”;
this.returnXYZ = function(){
alert(xyz);
}
}
someFunction.returnXYZ();
//can access xyz because it’s getting it’s getting it from an inner function

Learn More

That was pretty brief coverage for such big topics, so here are some places you can read more:

Hands On!

Well, I always like it when I read an article when the author gives me a way to see how I can put my new knowledge to use in real life, so that’s what I’m going to do for you! We’re going to create a myUser object that will give us a quick, easy way to get some of the user-centric information I wrote about in my recent article on User-Centric Javascript.
To start, we need to decide what will be included. I’m thinking:

  • A screen resolution property, that will return a string like “1024×768”
  • A referrer domain property that will return just the domain name, not the whole url
  • A browser property that will remap navigator.appName. jQuery’s support property offers more potential here, so I’m not going to get real fancy with browser sniffing.
  • A method for returning an array of GET variables
  • A time checker method that accepts a start and finish number, and returns true if the current hour is between those two
  • Two methods, setCookie() and getCookie(), for easy cookie management

This is mostly for educational purposes, so we aren’t going to get real deep with it, but it’ll be fun. The first thing to do is define a myUser constructor function, and add our properties:

function myUser(){
this.refDomain = document.referrer.substring(7).split(“/”)[0];
//get the referrer url, strip ‘http://’, and grab the part before the first slash

this.resolution = screen.width+ “x” +screen.height;
//combine height and width into string

this.browser = navigator.appName;
//the browser name
}

Now, we’ll write functions for the more advanced actions:

this.setCookie = function(name,value,date,path){
document.cookie = name+ “=” +value+ “;expires=” +date+ “;path=” +path+ “;”;
};
//simply accepts name, value, date and path and creates a cookie

this.getCookie = function(name){
var cookieStart = document.cookie.indexOf(cookieName+ “=”);
var cookieEnd = document.cookie.indexOf(“;”,cookieStart);
return document.cookie.substring(cookieStart,cookieEnd);
};
//scan document.cookie for our name, and then extract the value

this.GET = function(){
var search = document.location.search.substring(1), get = {};
var searchArray = (search.indexOf(“&”)!=-1) ? search.split(“&”) : [search];
for (arg in searchArray){
get[searchArray[arg].split(“=”)[0]] = searchArray[arg].split(“=”)[1];
}
return get;
};
//Take the search query, split it if it has multiple parameters,
//and then add each key/value pair to ‘get’, then return get.
/*NOTE: Object literals can also be used as associative arrays,
which is what I’ve done here- it’s a handy trick to know! */

this.ifTime(start,finish){
var hour = new Date().getHours();
var finish = (finish)? finish : 23;
if(hour > start && hour < finish){
return true;
}else{
return false;
}
};
//Simply compare the start and finish parameters to the current time.
//Notice that I’ve made finish be an optional parameter by providing
//the end of the day as a default.

And that concludes our user-centric class definition, it can now be used just like one of Javascript’s built-in objects. And although it has a lot of room for improvement/expansion, that is a real-life example of a neat thing you can do with Javascript objects. Feel free to experiment and expand!

The End

Thanks for reading, I hope you enjoyed! With your new Javascript object knowledge you’re ready to tackle bigger things, so next time I’ll be covering jQuery plugin development start-to-finish. Be sure to check back!

Written By Nick Parsons

Nick is the editor of Webitect and a developer + designer from Houston TX.

3 Comments

  1. Felipe Martyn

    November 5th, 2009 at 09:05 am

    Really nice.

    A great starting post about new functionalities that we, developers, could add to JS. I would suggest you to make of this, the start of a series about these more “advanced” topics.

    Although JavaScript isn’t a truly object oriented language. It’s more on the object based model, although we can implement it like with VB, another object based model. Really, this is the beauty of internet, were we can cooperate to make things bigger. It give its collaborators a sense of mission, where we all are building the pieces of a greater good.

    Thank you a lot

  2. Sarvesh

    November 7th, 2009 at 01:13 am

    This tutorial is more useful for NewBie’s in Javascript.

  3. Louis

    November 7th, 2009 at 11:28 pm

    Hey Nick,

    Thanks for mentioning my article from Six Revisions (6 Advanced JavaScript Techniques…, however the actual link is not working. Looks like you’ve got an empty anchor tag with no HREF attribute, so it’s just hovering but not clicking.

    Also, you misspelled my first name – should be “Louis” not “Lous”. Just thought I’d point those out. Thanks again for the mention, though.

What Do You Think?