面向对象高级之--利用纯面向对象和沙箱模式组织代码

    xiaoxiao2021-04-13  32

    // 此文 是利用纯面向对象基于jQuery 封装了一个tab栏切换和自动轮播的功能; 主要在于理解如何利用面向对象的方式组织代码,如何减少全局污染,以及利用单一职责来提高代码的 可阅读性 和 可维护性;

    // tabs.js文件整体代码如下:

    (function($) { 'user strict'; var Tab=function(config) { this.init(config); }; Tab.prototype={ constructor:Tab, //初始化属性和事件 init:function(config) { this.menuId=config.menuId||'tab-menu'; this.mainId=config.mainId||'tab-main'; this.$menu=$('#'+this.menuId).children(); this.$main=$('#'+this.mainId).children(); //维护一个index this.index=0; this.isAuto=config.isAuto||false; this.isAuto && this.autoPlay(); this.initEvent(); }, //单一职责:每个方法尽可能的单一 //抽离方法:绑定事件 , 实现tab切换 initEvent:function() { var that=this; this.$menu.on('click',function(){ //此处函数的this指向当前dom对象 that.index= $(this).index(); that.change(); }); }, //切换功能 change:function() { //此处的this是当前的实例对象 //var index= $(this).index(); this.$menu.eq(this.index).addClass('active').siblings().removeClass('active'); this.$main.eq(this.index).addClass('selected').siblings().removeClass('selected') }, //自动轮播功能 autoPlay:function() { var that=this; var set=function() { that.index++; if(that.index>3){ that.index=0; } that.change(); }; //清理计时器 var setId=setInterval(set,1000); this.$menu.mouseenter(function() { clearInterval(setId) }).mouseleave(function() { setId=setInterval(set,1000); }); }, //下一张功能 playNext:function() { this.index++; if(this.index>3){ this.index=0; } this.change(); }, //上一张功能 playPrve:function() { this.index--; if(this.index<0){ this.index=3; } this.change(); } }; //暴露在全局中 $.fn.tab=function(config) { //原型this是jQuery对象 new Tab(config); } })(jQuery)利用沙箱模式传入jQuery / $, 将 fn 作为jQuery中全局变量$的属性即可; //保证全局环境中只声明了一个变量  jQuery / $ , 将全局污染最小化; 最终最终,我们只需要引入文件,像jQuery一样调用时传入父元素id即可;

    <script src="js/jquery.js"></script> <script src="js/tabs.js"></script> <script type="text/javascript"> $('#wrapper').tab({ isAuto:true }); </script> html结构就省略了,根据代码结构自行脑补吧 

    个人日记 , 纯手打 ,欢迎指正 !

    转载请注明原文地址: https://ju.6miu.com/read-669019.html

    最新回复(0)