Creating custom objects in JavaScript

Tutorial introduction

All JavaScript coders eventually reach a stage where they would like to create and use their own objects, apart from the pre-built ones, such as document or Math. Custom objects allow you to build up your own personal JavaScript "toolbox" that extends beyond what the pre-build objects have to offer. After reading this tutorial, you'll learn how to create your very own JavaScript object, complete with custom properties and methods!

 

 

 

How to create your own basic object

Creating an object requires two steps:

  • First, declare the object by using an object function
  • Lastly, instantiate the newly created object by using the "new" keyword

Lets take this one step at a time. We will now proceed to create an object called "userobject", which, at this stage, does nothing:

Step 1: declare the object by using an object function

The first step towards creating an object requires us to define an object function. An object function is virtually identical in syntax as a regular function, although there are some differences which will surface later on. The object function is used to define and declare an object:

function userobject(parameter){
}

The parameter is optional, and with it, allows us to pass in values to an object. For example, in the pre-built object window.alert, the parameter is the text passed in to be alerted. Now, with just the above object function, we have in essence just created a new object called "userobject"! It does nothing at this stage, and will continue to do until we add in properties and methods. To use this object, all we have to do is instantiate it, by using the keyword "new".

Step 2: Instantiate the newly created object by using the "new" keyword

Once we've defined an object function, we have to instantiate it to actually use it.  Instantiating an object function means using the keyword "new" in front of the object name, and then creating an instance of the object by assigning it to a variable:

<script type="text/javascript">
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject("hi")
</script>

"myobject" is now an object...an instance of "userobject", to be exact.

If you're a little confused at this stage, consider a more familiar example:

var image1=new Image(20,20)

The above should be review to us; we created an instance of the pre-built image object by assigning it to the variable image1. Well, this familiar process is exactly what we'll doing with the custom object above.

If you're the kind that need to actually see and touch an object before you believe its an object, the window.alert method can help:

<script type="text/javascript">
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject("hi")
alert(myobject)
</script>

Are you convinced now?

 

How to add properties to your own object

Thus far, our object "userobject" cannot do anything but take up space in a document. With some properties, that should all change. To add properties to a user defined object, directly embed the properties into the object function, with each property proceeded by the keyword "this" plus dot (.): In the below example, we'll extend "userobject" to contain two properties, each containing a string of text:

function userobject(parameter){
this.firstproperty=parameter
this.secondproperty="This is the second property"
}

Now, to use these properties, simply access them like accessing any other property:

<script>
var myobject=new userobject("hi there.")
//alerts "hi there."
alert(myobject.firstproperty)
//writes "This is the second property"
document.write(myobject.secondproperty)
</script>

How to add methods to your own object

Adding methods to a user defined object is a bit more complicated. We need to first declare and define a function for each method, then associate this function with the object function. For the sake of simplicity, we will simply call functions defined for methods "method functions." Lets get a clean start, and create a new object called "circle" that will contain methods that compute the area and diameter of a circle, respectively.

The first step to adding methods is to implement the method functions. Method functions define what a method does:

//first method function
function computearea(){
var area=this.radius*this.radius*3.14
return area
}

//second method function
function computediameter(){
var diameter=this.radius*2
return diameter
}

In the above case, we've created two method functions, "computearea" and "computediamter", which calculates various aspects of a circle. The two functions, as you can see, are just functions, with one major distinction. Take the first one, for example:

function computearea(){
var area=this.radius*this.radius*3.14
return area

What the heck is this.radius? It looks like a property of a custom object to me (back up and see how a property is defined in a custom object). Since a method function will eventually be connected to the custom object, it has access to the properties of the object. We haven't defined the properties yet, but we will, and the method functions will use them in its calculation.

We will now associate the two method functions above to the new object "circle", so they become methods of the object:

<script type="text/javascript">
/*the below creates a new object, and gives it the two methods defined earlier*/
function circle(r){
//property that stores the radius 
this.radius=r
this.area=computearea
this.diameter=computediameter
}
</script>

Finally, to use these methods, instantiate the object, and access the methods just like any other method:

<script type="text/javascript">
var mycircle=new circle(20)
//alerts 1256
alert("area="+mycircle.area())
//alerts 400
alert("diameter="+mycircle.diameter())
</script>

As you can see, creating your own objects requires quite a bit of work, but can be very rewarding and even necessary as your JavaScript becomes more sophisticated.

 

 

Source: http://www.javascriptkit.com/javatutors/object.shtml

posted @ 2010-08-31 17:42  程序员天下  阅读(154)  评论(0编辑  收藏  举报