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

来源:互联网 发布:seo黑帽工具有哪些 编辑:程序博客网 时间:2024/06/16 04:36
// 此文 是利用纯面向对象基于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();//维护一个indexthis.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结构就省略了,根据代码结构自行脑补吧 得意

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

1 0
原创粉丝点击