Changes

Jump to: navigation, search

JavaScript Object Basics

181 bytes removed, 14:35, 15 April 2009
no edit summary
Built-in objects are objects that are provided with JavaScript to make your life as a JavaScript developer easier. In many of the examples given in this book we have used the document.write() mechanism to write text to the current web page. Whether you knew it or not, you have been using the write() method of the JavaScript built-in document ''object'' when you have run these scripts.
Document Object Model (DOM) Objects provide the foundation for creating dynamic web pages. The DOM provides the ability for a JavaScript script to access, manipulate, and extend the content of a web page dynamically (i.e . without having to reload the page). The DOM essentially presents the web page as a tree hierarchy of objects representing the contents and elements of the web page. These objects, in turn, contain ''properties'' and ''methods'' which that allow you to access and change parts of the web page.
Custom objects are objects that you, as a JavaScript developer, create and use. Creating a custom object is possibly the best way to fully understand what objects are, so in this chapter we will be looking at how to create custom objects before covering the Built-in and DOM Objects in later chapters.
== Creating and Using Object Instances ==
In the previous section we learned how to create an object definition. It is important to note that, at this point, we have only described what the object will do (we have bascically basically created blueprint of the object), we have not actually created an object we can work with (this is known as an ''object instance''). Object instances are created using the ''new'' keyword and are assigned to an object variable that will be used to reference the object. For example, in the following script we will create a new instance of the car object with the name myCar:
<pre>
We have also passed through parameters to initialize the properties of the object (make, model and color).
Next we need to understand how to call a method on an object and access an object property. This is achieved by using what is called ''dot notation '' on the name of the object instance:
To access a property:
</pre>
Lets Let's now bring all of this together in a complete example within an HTML page:
<pre>
<tt>objectType.prototype.propertyName</tt>
Following this syntax we could add a ''year'' property to an our ''car'' class and initialize it to the year '2001' using the following:
<pre>
When we now create an instance of the object it will contain this new property which can be read and manipulated in the same way as all the other properties in this class.
 
This chapter provided the essential information to get started using objects in JavaScript. In the following chapters we will explore the built-in objects provided with JavaScript.
== Summary ==

Navigation menu