jquery Picture Carousel (ii) Create objects with constructors and prototypes for inheritance

Source: Internet
Author: User

A small problem with the encapsulation done in the previous article is that the Carousel object cannot be reused on the same page, and this article will solve this problem by combining the constructor and prototype schema of JavaScript to create objects.

Friends who have not read the previous article can click here to view previous article (jquery Picture Carousel (one) Carousel implementation and encapsulation)

First of all, the problem above is that the Carsouel object in the above is defined in the literal way, so that Carsouel is an instance where the method of this object will conflict when you want to use it in multiple places, and eventually only the last one will be executed. By using constructors to define object Carsouel, each time you need to instantiate a new object with the new operator, you need to instantiate several objects with a few rotations on the page, so that you can meet the requirements. So, change the code to the following form.

function Carousel (){This.now =0;//the currently displayed picture indexthis.hasstarted =false;         //whether to start the carouselThis.interval =null;            //TimerThis.liitems =null;             //collection of LI elements to be carouselThis.len = 0;//Length of LiitemsThis.abox:null;                //DOM object containing the indicatorThis.bbox:null;                //DOM object with front and back buttons    /** initialization and control function * @param bannnerbox string containing the ID of the entire Carousel box or class * @param abox string containing the indicator's ID or class * @ Param Btnbox string contains the ID or class of the box with the front and back buttons*/This.startplay =function(bannnerbox,abox,btnbox) {//Initializing Object Parameters        varthat = This;  This. Liitems = $ (bannnerbox). Find (' ul '). Find (' Li ');  This. Len = This. Liitems.length;  This. Abox =$ (Bannnerbox). Find (Abox);  This. BBox =$ (Bannnerbox). Find (Btnbox); //let the first picture Show, dynamically create an indicator based on the number of carousel plots, and have the first indicator active, hiding the front and back buttons         This. Liitems.first (' Li '). css ({' Opacity ': 1, ' Z-index ': 1}). Siblings (' Li '). css ({' opacity ': 0, ' Z-index ': 0}); varADom = ' ';  for(vari = 0; I < This. Len; i++) {ADom+ = ' <a></a> '; } $ (ADom). AppendTo ( This. Abox);  This. Abox.find (' A:first '). addclass ("Indicator-active");  This. Bbox.hide (); //when the mouse moves into the banner diagram, stop the carousel and display the front and rear buttons, and then move out to start the carousel and hide the front and rear buttons$ (bannnerbox). Hover (function() {that.stop (); That.bBox.fadeIn (200); }, function() {That.start (); That.bBox.fadeOut (200);        }); //when the mouse moves into the indicator, the corresponding picture is displayed, and when it moves out, it continues playing         This. Abox.find (' a '). Hover (function() {that.stop (); varout = That.aBox.find (' a '). Filter ('. Indicator-active ')). index (); That.now= $( This). index (); if(out!=that.now) {That.play (out, That.now)}},function() {That.start ();        }); //Click the left and right buttons to display the previous or next one$ (Btnbox). Find (' A:first '). Click (function() {that.next ()}); $ (Btnbox). Find (' A:last '). Click (function() {That.prev ()}); //Start Carousel         This. Start ()}; //Previous functionThis.prev =function (){        varout = This. Now;  This. Now = (-- This. Now + This. Len)% This. Len;  This. Play (Out, This. Now);    }; //Next functionThis.next =function (){        varout = This. Now;  This. now = + + This. Now% This. Len;  This. Play (Out, This. Now);    }; /** * Play function * @param the index value of the picture that the out number is going to disappear * @param now number next the index value of the graph to be carousel*/This.play =function(out, now) { This. Liitems.eq (out). Stop (). Animate ({opacity:0, ' z-index ': 0},500). End (). EQ (now). Stop (). Animate ({opacity:1, ' z-index ' : 1},500);  This. Abox.find (' a '). Removeclass (' imgnum-active '). EQ (now). addclass (' indicator-active ');    }; //Start functionThis.start =function(){        if(! This. hasstarted) {             This. hasstarted =true; varthat = This;  This. Interval = SetInterval (function() {that.next (); },2000);    }    }; //Stop functionThis.stop =function() {clearinterval ( This. Interval);  This. hasstarted =false; }};

Called with the new operator, as follows:

    var banner1 = new CArousel ();     var banner2 = new CArousel ();     var Carousel ();    Banner1.startplay (' #J_bg_ban1 ', ' #J_bg_indicator1 ', ' #J_bg_btn1 ');    Banner2.startplay (' #J_bg_ban2 ', ' #J_sm_indicator2 ', ' #J_bg_btn2 ');    Banner3.startplay (' #J_bg_ban3 ', ' #J_sm_indicator3 ', ' #J_bg_btn3 ');

The above method can fulfill the requirements, but the analysis finds that this is almost identical to the method used in the previous article to copy objects using extend, where the new operator is actually copying the constructor completely out of the way as a fresh object, and there are common drawbacks to the methods mentioned above. That is, the intrinsic function is not reusable, and each time it is instantiated with the new operator, a new intrinsic function is created, which is also a disadvantage of using the constructor to customize the object individually.

The next function in the Carousel object, the Prev function, the Strat function, the Stop function are all common, and there is no problem in sharing these functions with multiple carousel parts, and the initialization function and the play function need to be called as private functions. objects created by using the constructor alone, the initialization method and the play method are re-created on each instance when a new instance is created using the new operator, which is exactly what we want, and the next method, the Prev method, the Start method, These common methods of the Stop method are also recreated, and creating multiple methods to accomplish the same task is completely unnecessary, so it is necessary to propose these common methods so that all instances of the Carousel object can be common so that the problem of function reuse can be solved.

By writing these common methods on the Carousel prototype object, you can share these methods through the prototype chain when creating a new instance of carousel, so that the common functions are reused and the code is as follows:

functionCarousel () { This. now = 0;//the currently displayed picture index     This. hasstarted=false;//whether to start the carousel     This. Interval =NULL;//Timer     This. Liitems =NULL;//collection of LI elements to be carousel     This. len = 0;//Length of Liitems     This. Abox =NULL;//DOM object containing the indicator     This. BBox =NULL;//DOM object with front and back buttons    /** initialization and control function * @param bannnerbox string containing the ID of the entire Carousel box or class * @param abox string containing the indicator's ID or class * @ Param Btnbox string contains the ID or class of the box with the front and back buttons*/     This. Startplay =function(bannnerbox,abox,btnbox) {//Initializing Object Parameters        varthat = This;  This. Liitems = $ (bannnerbox). Find (' ul '). Find (' Li ');  This. Len = This. Liitems.length;  This. Abox =$ (Bannnerbox). Find (Abox);  This. BBox =$ (Bannnerbox). Find (Btnbox); //let the first picture Show, dynamically create an indicator based on the number of carousel plots, and have the first indicator active, hiding the front and back buttons         This. Liitems.first (' Li '). css ({' Opacity ': 1, ' Z-index ': 1}). Siblings (' Li '). css ({' opacity ': 0, ' Z-index ': 0}); varADom = ' ';  for(vari = 0; I < This. Len; i++) {ADom+ = ' <a></a> '; } $ (ADom). AppendTo ( This. Abox);  This. Abox.find (' A:first '). addclass ("Imgnum-active");  This. Bbox.hide (); //when the mouse moves into the banner diagram, stop the carousel and display the front and rear buttons, and then move out to start the carousel and hide the front and rear buttons$ (bannnerbox). Hover (function() {that.stop (); That.bBox.fadeIn (200); }, function() {That.start (); That.bBox.fadeOut (200);        }); //when the mouse moves into the indicator, the corresponding picture is displayed, and when it moves out, it continues playing         This. Abox.find (' a '). Hover (function() {that.stop (); varout = That.aBox.find (' a '). Filter ('. Indicator-active ')). index (); That.now= $( This). index (); if(out!=that.now) {that.play (Out,that.now)}},function() {That.start ();        }); //Click the left and right buttons to display the previous or next one$ (Btnbox). Find (' A:first '). Click (function() {that.next ()}); $ (Btnbox). Find (' A:last '). Click (function() {That.prev ()}); //Start Carousel         This. Start ()}; /** * Play function * @param the index value of the picture that the out number is going to disappear * @param now number next the index value of the graph to be carousel*/     This. Play =function(out,now) { This. Liitems.eq (out). Stop (). Animate ({opacity:0, ' z-index ': 0},500). End (). EQ (now). Stop (). Animate ({opacity:1, ' z-index ' : 1},500);  This. Abox.find (' a '). Removeclass (' imgnum-active '). EQ (now). addclass (' indicator-active '); };} Carousel.prototype= {    //Previous functionPrev:function (){        varout = This. Now;  This. Now = (-- This. Now + This. Len)% This. Len;  This. Play (Out, This. Now)},//Next functionNext:function (){        varout = This. Now;  This. now = + + This. Now% This. Len;  This. Play (Out, This. Now); },    //Start functionStart:function(){        if(! This. hasstarted) {             This. hasstarted =true; varthat = This;  This. Interval = SetInterval (function() {that.next (); },2000); }    },    //Stop functionSTOP:function() {clearinterval ( This. Interval);  This. hasstarted =false; }};

Here, the prototype object of the Carousel object is rewritten by literal means, the next method, the Perv method, the Start method, and the Stop method are written into the Carousel prototype object, so that each instantiated object can share these methods. Of course, the method of instantiation is also using the new operator.

This combination of using constructors and prototypes is the most common way to create custom types, and we have completed the encapsulation of this simple carousel object.

jquery Picture Carousel (ii) Create objects with constructors and prototypes for inheritance

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.