🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#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'; } } }