#1、零污染
###什么是污染
- 全局變量
###為什么要零污染
-團隊開發中 自己開發的模塊 可能是為其他人提供 或者為以后提供
###解決方法
- 函數
-- 在函數內書寫方法和屬性
- 對象
-- 對象或者 面向對象編程的方式
- 立即函數 return
var my = (function(){
//代碼塊
return {
a: a,
b: b
}
})();
- 立即函數+閉包
(function(w){
var a = 'a';
var b = function(){}
//代碼塊
w.$ = {
a : a ,
b : b
};
})(window);
* * * * *
#2、模塊化
- 命名空間
var $ = {}
$.ui = {}
$.ui.pc = {}
$.ui.mobile = {}
* * * * *
#3、鏈式訪問
函數最后一步 返回this
* * * * *
#4、對象的方式調用
$('#id').show();
- 原理
var $ = function(selector){
this.elements = [];
return this.$all(selector);
}
$.prototype = {
$all:function(selector,context){
context = context || document;
this.elements = context.querySelectorAll(selector);
},
show: function(){
for(var i = 0;i <this.elements.length; i++ ){
this.elements[0].style.display = 'block';
}
}
}