Categories:

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>

cd.gif (3093 bytes)

Are you convinced now?