OOPObject-oriented programming
理解 一種編程方法
原理 利用Prototype屬性
的可繼承性實(shí)現(xiàn)
應(yīng)用
? tab組件
▼ 面向過程---------------------------------------------------------
$('.tab').on('click',function(){
var tab = $(this) ;
var i = $(this).index();
tab.siblings().removeClass('active');
tab.addClass('active');
tab.parents('.item').find('.panel-box').removeClass('active');
tab.parents('.item').find('.panel-box').eq(i).addClass('active');
});
▼ 面向?qū)ο?--------------------------------------------------------
function Tab(ct){ // 構(gòu)造函數(shù)Tab
this.ct = ct;
this.init();
this.bind();
}
Tab.prototype.init = function(){ // 初始化函數(shù)
this.$tab = this.ct.find('.tab');
};
Tab.prototype.bind = function(){ // 綁定事件
this.$tab.on('click',function(){
var tab = $(this) ;
var i = $(this).index();
tab.siblings().removeClass('active');
tab.addClass('active');
tab.parents('.item').find('.panel-box').removeClass('active');
tab.parents('.item').find('.panel-box').eq(i).addClass('active');
});
};
new Tab($('.item').eq(0));
new Tab($('.item').eq(1));
過程: 1 將面向過程的各部分功能劃分清晰
2 綁定在構(gòu)造函數(shù)上
3 綁定在新增加的this上
問題: 每個新組件都要執(zhí)行new命令來綁定this,才會生效敌蚜。如何一次使所有組件生效?
▼ 優(yōu)化封裝---------------------------------------------------------
舉例: var newTab1 = {
init:function(){ ...... }冬阳;
}
newTab1.init($('.item'));
思路: 1 以構(gòu)造函數(shù)的方式,將方法綁定在對象上,只是封裝方法
? 優(yōu)點(diǎn):
把方法作為對象的屬性來綁定兰英,防止全局變量的污染玷坠;
提高代碼復(fù)用性蜗搔,擴(kuò)展性,節(jié)省內(nèi)存八堡;
? 缺點(diǎn):
對象可獲得樟凄,可操控,有泄露風(fēng)險兄渺;
2 需要進(jìn)一步優(yōu)化缝龄,隱藏方法和變量 => 封裝對象
優(yōu)化: var newTab2 = (function(){
return{
init:function(ct){
ct.each(function(index,node){
new Tab($(node));
}) ;
}
}
})()
newTab2.init($('.item'));
分析: 1 newTab1是一個對象,所有方法只能以屬性方式添加
2 newTab2是一個立即執(zhí)行函數(shù)挂谍,結(jié)果由return返回叔壤,
方法可以屬性方式添加,也可在return內(nèi)添加 => 隱藏方法和局部變量
?曝光組件Exppsure
lazyLoad-Demo
功能:當(dāng)一個元素出現(xiàn)在可視范圍時凳兵,再讓此元素做出某種效果
函數(shù)--------------------------------------------------------
function Exposure ($target,callback){ //參數(shù):元素百新,回調(diào)函數(shù)
this.$target = $target;
this.init();
this.bind();
this.check($node);
}
Exposure.prototype.bind = function(){ //給元素綁定滾動事件
var _this = this;
$(window).on('scroll',function(){
_this.check();
})
}
Exposure.prototype.check = function(){ //檢查到元素出現(xiàn),就執(zhí)行回調(diào)函數(shù)
if(this.isShow(this.$target)){
this.callback(this.$target)
}
}
Exposure.prototype.isShow = function($node){ //判斷元素是否出現(xiàn)
var scrollH = $(window).scrollTop(),
winH = $(window).height(),
top = $node.offset().top,
if(top < winH + scrollH){
return true;
}else{
return false;
}
};
封裝-------------------------------------------------------------
var Lazy = (function(){
return{
init:function(){...}; // 初始化
once:function(){...};
}
})();
Lazy.one($('.always'), function($node){ // 調(diào)用組件庐扫,讓不同元素出現(xiàn)相應(yīng)效果
$node.text( $node.text() + 'and again');
});
Lazy.init($('.container img'), function($img){
$img.attr('src', $img.attr('data-src'));
});
分析:1 用構(gòu)造函數(shù)做出一個公用的曝光功能組件
2 留出多個接口供不同效果的元素使用(曝光加載圖片饭望,曝光加載文字...)