Saturday, December 20, 2008

Objects in JavaScript

Objects

We have already gone through values in JavaScript. What we only touched on though is that values in javascript can be of different types.

We have already seen number, string and array types. These are called primitive types and they are built-in to the language.

There are alot of other types, we will call them defined types. Defined objects are containers of sorts for other values. For instance, lets define a 'person' object. A person, in our example has a name, an age and a gender:

var newPerson = new Object();
newPerson.Name = "Jason";
newPerson.Age = "21";
newPerson.Gender = "M";


And now we can later modify or view the attributes (sometimes called slots) on that new person object.

There are many different object libraries available for use, but the most useful one for javascript is the Document Object Model; which we go over now.

The DOM

The Document Object Model(DOM) is the way in which we can manipulate the html page the user sees through javascript.

The primary way to access the HTML document is via the 'document' variable that is made available as a global variable for your javascript. Furthermore, we can access indvidual elements inside the document so long as they have an ID by 'document.getElementById'; we have already seen this be used.

This is where knowledge of HTML is useful. If you know the attributes that are valid for an object in html, this will often times translate easily to attributes we can call from javascript. For instance, in the sample photo gallery, we set the 'src' attribute on an image element, and this was reflected in the picture that was shown. Another example is when we called 'document.write(...)' in an early tutorial.

No comments:

Post a Comment