Creating custom objects in JavaScript

來源:互聯網
上載者:User

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" {
    function onclick()
    {
    adlinkMouseClick(event,this,0);
    }
    }" onmouseover="function onmouseover()
    {
    function onmouseover()
    {
    adlinkMouseOver(event,this,0);
    }
    }" onmouseout="function onmouseout()
    {
    function onmouseout()
    {
    adlinkMouseOut(event,this,0);
    }
    }" href="http://www.javascriptkit.com/javatutors/object2.shtml" target="_top">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 {
function onclick()
{
adlinkMouseClick(event,this,0);
}
}" onmouseover="function onmouseover()
{
function onmouseover()
{
adlinkMouseOver(event,this,0);
}
}" onmouseout="function onmouseout()
{
function onmouseout()
{
adlinkMouseOut(event,this,0);
}
}" href="http://www.javascriptkit.com/javatutors/object3.shtml" target="_top">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=parameterthis.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 functionfunction computearea(){var area=this.radius*this.radius*3.14return area}//second method functionfunction computediameter(){var diameter=this.radius*2return 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.14return 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=rthis.area=computeareathis.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 1256alert("area="+mycircle.area())//alerts 400alert("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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.