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

// 此文 是利用纯面向对象基于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结构就省略了,根据代码结构自行脑补吧  得意

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值