Don't Object to Objects
charles.russell — Thu, 07/29/2010 - 00:34
Sorry about being a little late but I have been swamped for the past several days. I will try to be more prompt in the future. In this posting I am going to talk about JavaScript objects.
For those of you who have not done any programming an object is a way of combing data, called properties, with the actions that affect that data, called methods. There is a set of special methods that reacts to external actions called events. Events may be standard events like click or a custom event you define. This may seem a little abstract so let's provide a more concrete example. Let's use a person. A person has physical characteristics like hair color, eye color, height, etc. these are the properties. People can also do things like walk, eat, drink, etc. these are the methods. An external event may be a tickle. So when the tickled event fires then execute the person's laugh method. This is the basic idea of object programming.
When discussing this subject it is important to realize that JavaScript is not a classical language. It is a prototype based language. This means that things are done very differently than in classical languages like PHP, C++, Java, Pascal and almost any other language you have ever heard of or used. While almost everything that can be done in these traditional languages can be done with JavaScript, however it will be different, sometimes very different. Do not plan on using what you know about programming objects in other languages. Just accept the way objects are done in JavaScript as being different, it will save you some confusion.
So how do you declare an object? Let's take the simplest case. MyCoolObject = {};
That's it, you now have an object called MyCoolObject. This object has no properties or methods so what is it good for? As it is, absolutely nothing. But remember this is a prototypical language. Unlike other languages you know, we can add methods and properties any time we want. Let's look at how to do this. MyCoolObject.prototype.myProperty = “Hello from My Cool Object”;
I have just now added a property to the object and gave it a string value. Methods can be added in a similar way: MyCoolObject.prototype.myMethod = function(){ alert(myProperty); };
In the previous example I created a method and used the value of the property I declared earlier in a call to the alert function. The result would be an alert box containing "Hello from My Cool Object" with an OK button. But this use of myProperty in this way is restricted to functions that are part of MyCoolObject. What if I want to reference myProperty from the outside of the MyCoolObject? That would be done with the dot operator like this: alert(MyCoolObject.myProperty).
In most languages that would be it, but in JavaScript there is more than one way to create an object. Let us start with a variant of the method we have used already. We can accomplish the same thing we did in our original like this: MyCoolObject = { myProperty: "Hello from My Cool Object", myFunctions: function(){ alert(myProperty); } };
This is called object literal notation. The construction of the object is similar but in this case I have created the property and method at the same time as I declared the object. This should be a little more familiar to those of you coming from classical languages. Properties and functions are declared in name value pairs. The name and value are separated by : and each pair is separated by a comma. This has uses outside of JavaScript, object literal notation forms the basis of the JSON data format.
This is very good but I can reset myProperty. You could do something like: MyCoolObject.myProperty = "Change happens";
I have now changed the value contained in myProperty. But what if I want to protect that value so that it cannot be used outside of MyCoolObject? This is called a private method or variable. The problem is that in JavaScript variables default public. The situation that we described is that we want private variables. This is useful for many reasons. It allows encapsulation of our data so that nothing can act directly on it in ways we don't want. So to make myProperty private we would rewrite the object like this: MyCoolObjectmyProperty = { var myProperty: "Hello from My Cool Object", myFunctions: function(){ alert(myProperty); } };
The var in the declarations makes the variable private to the object. One thing I want you to notice is that myFunction's value is a function. This is because in JavaScript a function is an object. It can be passed as a parameter, returned as a value and manipulated like any other object. This means that when you declare a function you are also creating an object. This also means that functions can have methods and properties of their own. So now let's declare this object using function notation: function MyCoolObject(){ var myProperty = " Hello from My Cool Object"; myFunction = function(){ alert (myProperty); } }
This notation has one other interesting implication, if this object is a function that means that it can be executed. If it can be executed we can use this ability to initialize settings within the object. In other languages this is called a constructor. Let's modify MyCoolObject to use this feature: function MyCoolObject (aString){ //The following statement uses the or behavior described in my previous posting Ilogical logicals var myProperty = aString || "Hello from My Cool Object" ; myFunction = function(){ alert(myProperty); } }
In the previous code I am passing in a parameter that may become the value. In this case the parameter called aString is optional. I am using the or operator described in a previous posting to set myProperty to a value. It will be aString if aString has a value otherwise it will be the original string. Now we have created objects how do we use them? Again it depends, if all you intend is a single instance you can just use myCoolObject just as is so to call myFunction. Here is an example of this straight call: myCoolObject.myFunction();
But you may need multiple instances of myCoolObject. For this you use the JavaScript reserved word new to create a new instance then make the call. Here is a sample of this usage: myInstance = new MyCoolObject(); myInstance.myFunction();
myInstance is now independent of any other instance of MyCoolObject. myInstance has its own independent values for variables isolated from any other instance. Any call to a property will get the values of the properties in this instance. This is just the beginning of JavaScript objects the use of prototype object property can be a subject in its own right. Next week I am going to get into another feature that enhances what we have already covered in this posting called Closure.
