Getting started with object-oriented JavaScript code

Source: Internet
Author: User
Tags html sample prev

Ext.: http://www.ibm.com/developerworks/cn/web/wa-oojavascript/

The JavaScript language contains several inline objects, just to name a few, such as Array , String and Date . However, if you want to create custom functions, you can use one of the available methods to create your own custom objects. There are many benefits to developing your custom object using the JavaScript language, one of which is that you can easily reuse these custom objects in multiple projects without modifying them. Also, custom objects can be connected to functions outside of the pre-built objects provided by the JavaScript language. You can combine this custom object with other custom objects to build a library to send to other web developers.

Properties and methods make objects functional and useful. The simplest way to understand the concept of an object is to imagine things in real life. For example, treat a dog as your object. A dog has properties such as legs, ears, tails, and possibly a collar. A dog also has methods such as barking, eating and sleeping. These methods can change the properties of a dog. For example, if a dog is barking, its ears are pricked up, and if the dog is sleeping, its ears should be drooping (unless, of course, the dog is a big Dane). Imagine using the dog object in your project. If you are interested in creating multiple dog objects, you will save a lot of time because they all have some common basic properties and methods. And, if you want to use the dog object in another project, you can easily reuse the objects you've already created.

The following are different ways to create objects using the JavaScript language:

    • ObjectFunction
    • Text symbol (Literal notation)
    • Object Constructors and prototyping

This article covers three ways to create a custom object using the JavaScript language. This article also demonstrates how to use each method to create a simple image library object.

To start reading this article, you need to have a basic understanding of the JavaScript language. Download the sample code from the download section to run the samples. If you want to learn more about the basics of JavaScript, see the articles referenced in the Resources section.

ObjectFunction

ObjectFunctions are one of the simplest ways to create objects using the JavaScript language. The JavaScript language contains a Object function called, which can be new associated with an operator to create an object. Objecta function is the starting point for any custom functionality you want to get by creating an object. To refer to an new object created using operators and Object functions, you only need to specify a variable name for it (see Listing 1).

Listing 1. Listing 1. Use Objectfunction to create a custom object
var Gallery = new Object ();

To make an Gallery object work, you can give it functionality by adding properties and methods. Listing 2 contains Gallery three properties and three methods that have been added to the object.

Listing 2. Listing 2. A custom that contains properties and methods GalleryObject
var Gallery = new Object (); Gallery.currentindex = 0; Gallery.images = new Array (' istockphoto_14149033.jpg ', ' istockphoto_14232771.jpg ', ' istockphoto_14667148.jpg '); Gallery._loopinterval = SetInterval (' Gallery.next () ', 2500); Gallery.next = function () {    if (Gallery.currentindex < (gallery.images.length-1))    {        gallery.currentindex++;    }    else gallery.currentindex=0;    Gallery.display ();} Gallery.prev = function () {    if (Gallery.currentindex > 0)    {        gallery.currentindex--;    }    else gallery.currentindex= (gallery.images.length-1);    Gallery.display ();} Gallery.display = function () {    var photogallery = document.getElementById (' photo-gallery ');    var currentimage = Gallery.images[gallery.currentindex];    PHOTOGALLERY.SRC = ". /assets/img/"+currentimage;}
_loopIntervalThe number in the property

You can _loopInterval increase or decrease the time between images by modifying the numbers in the properties.

GalleryThe properties of the object are as follows: CurrentIndex , Images and _loopInterval . To define them as Gallery properties of an object, you simply assign them to the Gallery object by using "point syntax"-Attaching a point, then the variable name, and finally assigning a value to the variable. The method used in Listing 2 is Next , Prev and Display . To define them as Gallery methods of an object, you can use point syntax and specify a function for each method.

Nextand Prev methods use the properties in this object. CurrentIndexproperty to recognize the Images current index of an array, so when you increase or decrease the index, it references different array items. Imagesproperty is an array that is used to store the image that is being displayed in the library. _loopIntervalproperty automatically cycles through the images in the library every 2.5 seconds.

Examples of HTML used in this article

The other examples in this article use the HTML file in Listing 4. Only Gallery objects are changed based on the type of object you are using.

GalleryObjects are Next similar to Prev methods-the former increases Images the current index of the array, whereas the latter, in contrast, causes Display different images to be displayed each time the method is called.

To invoke a method in this object, such as a Next method, you simply reference the Gallery object, then a point, then the name of the method ( Next ), and finally the parentheses (see Listing 3).

Listing 3. Listing 3. Calling a custom GalleryObject in the NextMethod
Gallery.next ();

To actually apply this object, you can easily create some controls to explore Images the images in the array. First, you need to include a JavaScript file, which is an external file named Gallery.js. Then you simply add an HTML img tag, display the image and add a link to control the front and back navigation (see Listing 4).

Listing 4. Listing 4. Contains a custom GalleryHTML sample files for objects and Gallery functions

Back to top of page

Text symbols

Another way to create objects using the JavaScript language is through text notation (literal notation), which requires support for JavaScript version 1.2 and above. As with Object objects created with functions, text symbols can contain properties and methods.

Creating a custom JavaScript object with text symbols is similar to creating an associative array using another programming language. To create an object using a text symbol, simply assign a variable to a curly brace, as shown in Listing 5.

Listing 5. Listing 5. Create a custom object using text symbols
var Gallery = {};

To define the properties of an object created with a text symbol, you need to add a colon between the variable name and the variable value, and separate all the attributes with commas, as shown in Listing 6.

Listing 6. Listing 6. Add attributes to a custom object using text symbols
var Gallery = {    images:new Array (' istockphoto_14149033.jpg ', ' istockphoto_14232771.jpg ', ' istockphoto_14667148. JPG '),    currentindex:0,    _loopinterval:setinterval (' Gallery.next () ', 2500)};

You use an object created by a text symbol to define the method in a way that is similar to defining a property: Declare the variable first, then add a colon, and then the function. To define different methods in an object, you need to separate them with commas (see listing 7).

Listing 7. Listing 7. Add a method to a custom object using a text symbol
var Gallery = {    next:function ()    {        if (Gallery.currentindex < (gallery.images.length-1)) gallery.currentindex++;        else gallery.currentindex=0;        This. Display ();    },    prev:function ()    {        if (Gallery.currentindex > 0) gallery.currentindex--;        else gallery.currentindex= (gallery.images.length-1);        This. Display ();    },    display:function ()    {        var photogallery = document.getElementById (' Photo-gallery ' );        var currentimage = this. Images[this. Currentindex];        PHOTOGALLERY.SRC = ". /assets/img/"+currentimage;    };

ObjectAnother difference between using a function and a text symbol is that you do not have to provide the object name each time you define properties and methods. Listing 8 shows a complete example of an object that uses a text symbol Gallery .

Listing 8. Listing 8. A custom that uses text symbolsGalleryObject
var Gallery = {    images:new Array (' istockphoto_14149033.jpg ', ' istockphoto_14232771.jpg ', ' istockphoto_14667148. JPG '),    currentindex:0,    _loopinterval:setinterval (' Gallery.next () ', 2500),    next:function ()    {        if (Gallery.currentindex < (gallery.images.length-1))        {            gallery.currentindex++;        }        else gallery.currentindex=0;        This. Display ();    },    prev:function ()    {        if (Gallery.currentindex > 0)        {            gallery.currentindex--;        }        else gallery.currentindex= (gallery.images.length-1);        This. Display ();    },    display:function ()    {        var photogallery = document.getElementById (' Photo-gallery ' );        var currentimage = this. Images[this. Currentindex];        PHOTOGALLERY.SRC = ". /assets/img/"+currentimage;    };

To use this object, you can put it in the HTML file that you used in Listing 4. The rest of the code, including function calls, is the same.

Objectthe only drawback to using functions or text symbols is that you cannot instantiate them multiple times. For example, in the initial time that an object is created, you can only use operators for both types of objects new , which means that you cannot reuse objects to create additional instances. For the example in this article, if you want to create multiple libraries in a single HTML file, you need to include JavaScript files multiple times and give the library a different name each time, which causes many duplicate objects to have different names. Therefore, for this scenario, these object types are not good choices. On the other hand, these object types are very useful if you only need to use objects once. Create an object that can be instantiated more than once, and you need to use object constructors and prototyping.

Back to top of page

Object Constructors and prototyping

When you need an object that can be instantiated more than once, the object constructor and prototype is the answer. The object constructor is like any other function, but when you name the function, you need to name the function the name of the object you created in this function. In this case, the object is named Gallery . However, because you want the library object to have the ability to create multiple instances, here I name it GalleryObj .

When you start adding properties and methods to an object constructor, it begins to become different. I personally do not add methods to the constructor, because although this can be done, this is not a good form. When you add a property or method to an object function, you can use the keyword before the property or method name to assign them to the object itself (see Listing 9).

Listing 9. Listing 9. Defining properties in the object constructor
function Galleryobj () {this    . Images = new Array (' istockphoto_14149033.jpg ', ' istockphoto_14232771.jpg ', ' istockphoto_14667148.jpg ');    This. Currentindex = 0;}

I prefer to use keywords when compared to adding methods to object Constructors prototype . prototypekeywords provide the ability to create inheritance in the JavaScript language. For example, when you want an object to inherit a method after it is defined by an object constructor, using a prototype keyword basically lets you connect the method to an object, and then allows all instances of the object to use that method (see listing 10).

Listing 10. Listing 10. UseprototypeKeyword to add a method to an object
GalleryObj.prototype.Next = function () {    if (this). Currentindex < (this. images.length-1))    {this        . currentindex++;    }    else this. currentindex=0;    This. Display ();}

In Listing 11, you can see the objects that use constructors and prototypes Gallery .

Listing 11.清单 11. 一个使用对象构造函数和原型化的自定义 GalleryObj 对象
  function Galleryobj () {this.    Images = new Array (' istockphoto_14149033.jpg ', ' istockphoto_14232771.jpg ', ' istockphoto_14667148.jpg '); This. Currentindex = 0;} GalleryObj.prototype.Next = function () {if (this). Currentindex < (this. Images.length-1)) {this.    currentindex++; } else this.    currentindex=0; This. Display ();} GalleryObj.prototype.Prev = function () {if (this). Currentindex > 0) this.    currentindex--; else this. Currentindex= (this.    IMAGES.LENGTH-1); This. Display ();}    GalleryObj.prototype.Display = function () {var photogallery = document.getElementById (' photo-gallery '); var currentimage = this. Images[this.    Currentindex]; PHOTOGALLERY.SRC = ". /assets/img/"+currentimage;} var Gallery = new Galleryobj (); SetInterval (' Gallery.next () ', 2500);  

为了使用相同的 HTML 文件,我把对象命名为 GalleryObj,这样当您把它初始化时,您可以把实例命名为 Gallery。另一个不同点是自动推进库图像的间隔在每个实例中而不是对象中定义,这使您可以单独控制每个库实例的间隔。

现在如果您有兴趣创建其他 GalleryObj 对象的实例,您可以轻松定义一个新实例,如清单 12 所示。

清单 12. 清单 12. 创建自定义 GalleryObj 对象的另一个实例
var Gallery2 = new GalleryObj();

如您所见,自定义构造函数非常强大,因为它可以让您创建一个对象的无数实例。原型化也非常强大,因为它可以使您在运行时添加方法,之后这个方法可以链接到那个对象的所有实例。

回页首

原型化核心 JavaScript 对象

既然您了解了原型化,现在可以查看如何把自定义方法添加到核心 JavaScript 对象。有时您需要额外的功能,但并不一定是自定义对象。例如,假设您需要获取您的库的 Images 数组中的一个特定项目的索引。您可以通过使用 prototype 关键字向对象中添加新的方法来扩展 Array 对象,而不是写一个随机的不可重用的函数(见清单 13)。

清单 13. 清单 13. 使用 prototype 关键字向 JavaScript 语言中的核心 Array 对象添加方法
Array.prototype.GetIndex = function(item){    for(var i=0; i<this.length; i++)    {        if(this[i] == item) return i;    }}

要使用您添加到 Array 对象中的新方法,您可以轻松调用它,就像从您创建的任何数组调用其他任何函数一样。清单 14 包含一个名为 GetIndex 的Images 数组,它可以获取数组中特定图像的索引。

清单 14. 清单 14. 使用 prototype 关键字向核心 Array 对象中添加方法
 

扩展 JavaScript 语言中的核心对象可以使您给已经存在的对象添加功能。当您想到自己能扩展 Array 对象的功能,然后在您的任何项目中重用扩展的功能时,那感觉一定棒极了!

回页首

结束语

本文所涉及的每种方法都有自己的作用。 Object 函数和文本符号相似,至于选择使用哪个确实基于开发人员的个人爱好。对于不需要被多次实例化的对象来说,两者都是很好的选择。当需要创建可以被多次实例化的对象时,对象构造函数和原型化是比较理想的。

在 JavaScript 语言中创建自定义对象使您在保持代码简单有序的同时还能够创建更复杂的功能。我希望本文可以激发您在 JavaScript 项目中使用自定义项目创建复杂的交互性的想法。

Getting started with object-oriented JavaScript code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.