1.高级单例设计模式:闭包+单例的结合,也是最早期的JS模块化思想
//----------
var weatherModule=(function () {
var time = '2020-11-01';
function queryData() {}
function changeCity() {}
return {
queryData:queryData,
changeCity:changeCity
};
})();
var infoModule=(function () {
var time = '2020-10-31';
function changeCity() {}
weatherModule.queryData();
return {
changeCity:changeCity
};
})();
2.惰性思想
// window.getComputedStyle(元素):获取当前元素经过浏览器计算的样式「返回样式对象」
// 在IE6~8中,不兼容这种写法,需要使用 “元素.currentStyle” 来获取
// “属性 in 对象” 检测当前对象是否有这个属性,有返回true,反之false
function getCss(element, attr) {
if ('getComputedStyle' in window) {
return window.getComputedStyle(element)[attr];
}
return element.currentStyle[attr];
}
var body = document.body;
console.log(getCss(body, 'height'));
console.log(getCss(body, 'margin'));
console.log(getCss(body, 'background'));
//-------优化思想:第一次执行getCss我们已经知晓是否兼容了,第二次及以后再次执行getCss,则不想在处理兼容的校验了,其实这种思想就是“惰性思想”「懒,干一次可以搞定的,绝对不去做第二次」
var flag = 'getComputedStyle' in window;
function getCss(element, attr) {
if (flag) {
return window.getComputedStyle(element)[attr];
}
return element.currentStyle[attr];
}
function getCss(element, attr) {
// 第一次执行,根据是否兼容,实现函数的重构
if ('getComputedStyle' in window) {
getCss = function getCss(element, attr) {
return window.getComputedStyle(element)[attr];
};
} else {
getCss = function getCss(element, attr) {
return element.currentStyle[attr];
};
}
// 为了保证第一次也可以获取信息,则需要把重构的函数执行一次
return getCss(element, attr);
}
var body = document.body;
console.log(getCss(body, 'height'));
console.log(getCss(body, 'margin'));
console.log(getCss(body, 'background'));
3.柯理化函数思想
// 函数柯理化:预先处理的思想「形成一个不被释放的闭包,把一些信息存储起来,以后基于作用域链,访问到事先存储的信息,然后进行相关的处理,所有符合这种模式(或者闭包应用的)都被称为柯理化函数」
// x:预先存储的值
function curring(x) {
// x->10
return function (...args) {
// args->[20]/[20,30]
args.unshift(x);
// 数组求和
var total = eval(args.join('+'));
return total;
};
}
function curring(x) {
return function (...args) {
args.unshift(x);
return args.reduce((result, item) => result + item);
};
}
var sum = curring(10);
console.log(sum(20)); //10+20
console.log(sum(20, 30)); //10+20+30
const add1 = x => x+1;
const mul3 = x=> x+2
function compose(...funcs) {
return function aa(x){
if(funcs.length === 1){
return typeof funcs[0] !== 'function' ? x :funcs[0](x)
}
return funcs.reduceRight((result, item)=>{
if(typeof item !== 'function') return result
return item(result)
},x)
}
}
var bb = compose()
var resule = bb(999)
console.log(resule);