JavaScript常见封装方法

1.最简单的,使用变量,然后用匿名函数包裹,不封装

2.对象字面量简单封装(不完整的模块模式,因为无法达到变量、方法私有效果。不过确实有分离和组织代码的能力,也就算一种简略的模块模式的实现方式)

var Carousel = {
	init: function(){...},
	bind: function(){...},
	showPre: function(){...},
	showNext: function(){...}
};

3.原型构造器模式封装

function Carousel(){
	this.init();
}

Carousel.prototype = {
	init: function(){...},
	bind: function(){...},
	showPre: function(){...},
	showNext: function(){...}
};

4.模块模式与原型构造器模式绑定多个:使用一个数组保存实例

var CarouselCenter = (function(){

	var carouselList = [];


	function init($carousel){
		$carousel.each(function(){
			var $cal = $(this);
			if($cal.hasClass('init')){
				return;
			}
			carouselList.push( new Carousel($cal) );
			$cal.addClass('init')
		});

	}

	function getList(){
		return carouselList;
	}

	function Carousel($carousel){
	}

	Carousel.prototype = {

		bind: function(){
			var _this = this;
			this.$pre.on('click', function(){
				_this.showPre();
			});
			this.$next.on('click', function(){
				_this.showNext();
			});
		},

		showPre: function(){
			this.$ct.prepend(this.$ct.children().last());
			this.$ct.css('left', 0-this.imgWidth);
			this.$ct.animate({'left': 0});
		},

		showNext: function(){
			var $ct = this.$ct;
			$ct.animate({'left': 0-this.imgWidth},function(){
				$ct.append($ct.children().first());
				$ct.css('left', 0);
			});
		}
	};


	return {
		init: init,
		getList: getList
	}

})(); 

// 调用	
// CarouselCenter.init($('#c1'))
// CarouselCenter.init($('#c2'))
// CarouselCenter.init($('#c2')) //不会重复绑定

// CarouselCenter.init($('.carousel')) 

5.通用写法

(function(window,$){
	function Carousel(){

	};

	Carousel.prototype = {

	};

	window.Carousel = Carousel;
})(window,jQuery)

ps:

模式目的:编写易于维护的代码,其中一个最重要方面是能够找到代码中重复出现的主题并优化它们。

posted @   万里秋山  阅读(499)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示