The prototype object of JavaScript

來源:互聯網
上載者:User
 

原文:http://www.lukfor.com

The prototype object of JavaScript

No, we're not going to discuss how to construct a new version of JavaScript in this tutorial. The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object. I know, I'm starting to sound a little geeky already, but hay, JavaScript isn't just about fun and games...it's important to learn the serious side of it too.

A little background first...

In JavaScript, you're allowed to add custom properties to both prebuilt and custom objects. Here's an example of each:

//adding a custom property to a prebuilt objectvar myimage=new Image()myimage.size="26k"/*adding a custom property to the custom object "circle"*///First, create the custom object "circle"function circle(){}var smallcircle=new circle()smallcircle.pi=3.14159

A custom property added this way only exists for that instance of the object. If I were to spit out another instance of circle(), called "bigcircle", for example, bigcircle.pi would by default return "undefined" until I go over the process again of first defining bigcircle.pi, as with smallcircle.

There are times when you'll want to add a custom property that's only reflected on a particular instance of an object, and times, when you just wished all instances of the object would  recognize the custom property already. For example, all circles- and not just small circles- have a pi, so it's reasonable to assume you'd like the custom property "pi" added in a way so that it's default across all instances of the circle object. That's where the prototype object of JavaScript comes in.

Using the prototype object to add custom properties to objects

The prototype object is here to help when you wish to quickly add a custom property to an object that is reflected on all instances of it. To use this object, simply reference the keyword "prototype" on the object before adding the custom property to it, and this property is instantly attached to all instances of the object. A demonstration is worth a thousand words, so I'll show one right now: Let's define the custom property "pi" in the above in a way so it's a default property of all instances of circle():

//First, create the custom object "circle"function circle(){}circle.prototype.pi=3.14159

Having done the above, all instances of circle() now has the pi property prebuilt into them.

There is an important thing to take note at this point in the tutorial. While you are free to use the prototype object on any custom objects, this is NOT the case with prebuilt ones (such as image, string etc). JavaScript only allows you to "prototype" prebuilt objects that are created with the new keyword, such as the following:

  • The image object
  • The string object
  • The date object
  • The Array object

In the final part of this tutorial, I'll demonstrate an example involving prototyping a prebuilt JavaScript object.

Let's move on to see how to use the prototype object to add custom methods.

Using the prototype object to add custom methods to objects

The prototype object can also help you quickly add a custom method to an object that is reflected on all instances of it. To do so, simply create the object method as usual, but when attaching it to the object (you guessed it),  use "prototype" beforehand. Let's extend our circle object so it contains a default method that does something simple, like alert the value of PI:

//First, create the custom object "circle"function circle(){}circle.prototype.pi=3.14159// create the object methodfunction alertmessage(){alert(this.pi)}circle.prototype.alertpi=alertmessage

Now, all instances of the circle object contain a alertmessage() method!

Putting things into perspective- Examples

If you're having a hard time staying awake while reading this tutorial, I can't say I blame you. The prototype object of JavaScript isn't exactly as flashy and fun to learn as say, document.bgColor or window.open, and the rewards aren't always instant. But if you're at all interested in extending JavaScript and creating your own objects and libraries, the prototype object is a must learn. Allow me to show you now a couple of practical examples on using the prototype object of JavaScript:

-Example 1-Extending functionality to the pre-built string() object

As mentioned earlier in this tutorial, the prototype object can be used on pre-built JavaScript objects created with the new keyword to add custom properties/ methods to them. Let's see an interesting example on how to extend the prebuilt String object of JavaScript to include a method that writes any string backwards when called upon:

<script type="text/javascript">/*code for extending String object with method that writes text backwards*///core custom method for writing text backwardsfunction outputbackwards(){for (i=this.length-1;i>=0;i--)document.write(this.charAt(i))}//Attach custom method to string objectString.prototype.writeback=outputbackwards</script>

The above code may not look like much, but it just added a whole new functionality to the default string object- the ability to output any text backwards! Here are a few examples:

<script type="text/javascript">var message1="Welcome to my site!"message1.writeback()var message2="Today is a beautiful day"message2.writeback()</script>

Output:

!etis ym ot emocleW
yad lufituaeb a si yadoT

We're playing Frankenstein with the JavaScript language!

-Example 2-Extending functionality to a custom JavaScript object

For the most part, you'll probably be using the prototype object to extend and expand a custom JavaScript object you created earlier. JavaScript developers who create custom objects often know that the traditional way of assigning custom properties/ methods to an object isn't exactly a walk in the park (See "Creating Custom objects in JavaScript"). With the prototype object at hand, however, this process becomes a lot simpler and intuitive.

I'll quickly demonstrate the concept by first creating a "dummy object", and using the prototype object- and only this object- to equip the dummy object with properties and methods:

<script type="text/javascript">//create dummy objectfunction dummy(){}//Create custom propertyfunction dummyproperty(){}//Create custom methodfunction dummymethod(){}dummy.prototype.prop=dummypropertydummy.prototype.method=dummymethod</script>

The key to take away from this example is how easy it is to attach a property/ method to an object (so it's reflected on all instances of it)- by using the prototype object of JavaScript.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.