jQuery中封装
(function(){
var jQuery = function(){
return new jQuery.prototype.init();
}
jQuery.prototype = {
init:function(){
},
css:function(){
return this; //链式调用
console.log(1)
},
animate:function(){
}
}
jQuery.prototype.init.prototype = jQuery.prototype;
window.$ = window.jQuery = jQuery; // 暴露
})()
//jQuery 得到的是什么?init构造函数的实例
//jQuery().css()调用jQuery.prototype上的方法
//原型共享
//为什么使用闭包 1.保护变量免污染 2.全局对象在查找的时候,效率会比私有作用域慢 3.延长生命周期
//(function(){})() 匿名自调
// !function(w){}(window) ! 转化为表达式 或者 +
<script>
// jquery 对外暴露的实例对象
jQuery().css() //1
</script>
封装方法,初级封装:
;
(function () {
var _global;
var tool = {
add: function (n1, n2) {
return n1 + n2
},
sub: function (n1, n2) {
return n1 - n2
},
mul: function (n1, n2) {
return n1 * n2
},
div: function (n1, n2) {
return n1 / n2
}
}
_global = (function(){ return this || (0,eval)('this');}())
//(0,eval('this))获取上下文对象
//环境
if(typeof module!=="undefined"&& module.exports){
module.exports = tool;
}else if(typeof define === "function" && define.amd){
define(function(){
return tool
})
}else{
!('tool' in _global) && (_global.tool = tool);
}
//window.$ = window.tool = tool;
})(window);
console.log(tool.add(1,1))
此代码有问题,没有设置默认值,下面是加强版
;(function(undefined){
var _global;
function result(args,type){
var argsArr = Array.prototype.slice.call(args);
if(argsArr.length == 0) return 0;
switch(type){
case 1 :return argsArr.reduce(function(p,c){return p+c});
case 2 :return argsArr.reduce(function(p,c){return p-c});
case 3 :return argsArr.reduce(function(p,c){return p*c});
case 4 :return argsArr.reduce(function(p,c){return p/c});
case 5 :return argsArr.reduce(function(p,c){return p%c});
default: return 0;
}
}
function Calculate(){}
Calculate.prototype.add =function(){console.log(result(arguments,1)); return this} // 链式调用 return this
Calculate.prototype.sub =function(){console.log(result(arguments,2)); return this}
Calculate.prototype.mul =function(){console.log(result(arguments,3)); return this}
Calculate.prototype.div =function(){console.log(result(arguments,4)); return this}
Calculate.prototype.sur =function(){console.log(result(arguments,5)); return this}
_global = (function(){ return this || (0,eval)('this');}())
//(0,eval('this))获取上下文对象
if(typeof module!=="undefined"&& module.exports){
module.exports = Calculate;
}else if(typeof define === "function" && define.amd){
define(function(){
return Calculate
})
}else{
!('Calculate' in _global) && (_global.Calculate = Calculate);
}
})();
var plugin = new Calculate()
plugin.add(2,1).sub(2,1).mul(2,1).div(2,1).sur(2,1)