jquery Picture Carousel (ii) Create objects using constructors and prototypes to implement inheritance _jquery

Source: Internet
Author: User
Tags inheritance prev setinterval

One small problem with the encapsulation that was completed in the previous article is that the Carousel object cannot be reused on the same page, and this article solves this problem by combining the JavaScript constructor with the prototype schema to create the object.

Friends who have not read the previous article can click here to view the previous article (jquery Image Carousel Implementation and encapsulation (i))

First of all, the above problem, the Carsouel object in the above is defined in a literal way, so that Carsouel is an example, when you want to use in multiple places, the object's method will conflict, and eventually only the last one will be executed. By using the constructor to define the object Carsouel, each need to use the new operator only to instantiate a novel object, the page requires several rotations on the instantiation of several objects, so that can meet the needs. So, change the code to the following form.

Function Carousel () {this.now = 0; The currently displayed picture index this.hasstarted = false//whether to start the carousel this.interval = null;//Timer this.liitems = null;//To be carousel         Li element Set this.len = 0;        The length of the Liitems is this.aBox:null;        The DOM object this.bBox:null that contains the indicator; Dom object with front and rear buttons/** * initialization and control function * @param bannnerbox string contains the ID or class * @param the entire carousel box Abox string contains the ID of the box for the indicator or CL 
    Ass * @param btnbox string contains the ID or class/This.startplay = function (Bannnerbox,abox,btnbox) {//initialization object parameters of the front and rear button boxes
    var that = 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 graphs, and let the first indicator be active, hiding the front and rear button this.liItems.first (' Li '). css ({' Opacity ': 1, ' Z-index ': 1}).
    Siblings (' Li '). css ({' opacity ': 0, ' Z-index ': 0});
    var aDom = ';
    for (var i = 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, move out and start the carousel and hide the front and Back 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 the This.aBox.find (' a ') is continued to play when it is removed. Hover (function () {that.stop ();
      var out = 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 button to display the previous or next $ (btnbox). Find (' A:first '). Click (function () {That.next ()});
    $ (Btnbox). Find (' A:last '). Click (function () {That.prev ()});
  Start the Carousel This.start ()};
    Previous Functions This.prev = function () {var out = This.now;
    This.now = (--this.now + this.len)% This.len;
  This.play (out, This.now);
  };
    This.next = function () {var out = This.now;
    This.now = ++this.now% This.len;
  This.play (out, This.now);
  }; /** * Play function * @param out number The index value of the picture to disappear * @param now number the index value of the graph to be carousel */this.play = function {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 function This.start = functions () {if (!this.hasstarted) {this.hasstarted = true;
      var that = this;
      This.interval = setinterval (function () {that.next ();
    },2000);
  }
  };
    Stop Functions this.stop = function () {clearinterval (this.interval);
  this.hasstarted = false; }
};

When called, the new operator is used, as follows:

var banner1 = new Carousel ();
  var banner2 = new Carousel ();
  var banner3 = new 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 realize the requirement, but careful analysis found that this is almost the same as using extend to copy objects in the previous article, where the new operator actually replicates the constructor completely as a new object, and there are common drawbacks to the methods mentioned above, That is, the intrinsic function cannot be reused, and every time the execution is instantiated with the new operator, a new intrinsic function is created, which is also the disadvantage of using the constructor to customize the object separately.

In the Carousel object, the next function, the Prev function, the Strat function, the Stop function is all shared, and multiple rotations share these functions completely without problems, and the initialization and play functions need to be called as private functions. The object created by using the constructor alone, the initialization method and the play method are created again on each instance when a new instance is created using the operator, which is exactly what we want, and the next method, the Prev method, the Start method, The Stop method can also be recreated, and the creation of multiple methods for accomplishing 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 shared so that the problem of function reuse can be solved.

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

Function Carousel () {this.now = 0;     The currently displayed picture index this.hasstarted= false;      Whether to start the carousel this.interval = null;       Timer this.liitems = null;          The LI element Set this.len = 0 to be carousel;        The length of the liitems is this.abox = null;        The DOM object containing the indicator this.bbox = null; Dom object with front and rear buttons/** * initialization and control function * @param bannnerbox string contains the ID or class * @param the entire carousel box Abox string contains the ID of the box for the indicator or CL 
    Ass * @param btnbox string contains the ID or class/This.startplay = function (Bannnerbox,abox,btnbox) {//initialization object parameters of the front and rear button boxes
    var that = 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 graphs, and let the first indicator be active, hiding the front and rear button this.liItems.first (' Li '). css ({' Opacity ': 1, ' Z-index ': 1}).
    Siblings (' Li '). css ({' opacity ': 0, ' Z-index ': 0});
    var aDom = ';
    for (var i = 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, move out and start the carousel and hide the front and Back 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 the This.aBox.find (' a ') is continued to play when it is removed. Hover (function () {that.stop ();
      var out = 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 button to display the previous or next $ (btnbox). Find (' A:first '). Click (function () {That.next ()});
    $ (Btnbox). Find (' A:last '). Click (function () {That.prev ()});
  Start the Carousel This.start ()}; /** * Play function * @param out number The index value of the picture to disappear * @param now number 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 function prev:function () {var out = This.now;
    This.now = (--this.now + this.len)% This.len;
    This.play (Out,this.now)},//Latter function next:function () {var out = This.now;
    This.now = ++this.now% This.len;
  This.play (Out,this.now);
      },//Start function start:function () {if (!this.hasstarted) {this.hasstarted = true;
      var that = this;
      This.interval = setinterval (function () {that.next ();
    },2000);
    },//Stop function stop:function () {clearinterval (this.interval);
  this.hasstarted = false; }
};

In this case, the Carousel object's prototype object is rewritten, and 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 instantiated method also uses the new operator.

This combination of constructors and prototypes is the most common way to create a custom type, so we've done this simple Carousel object encapsulation.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

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.