8.JS高阶编程-闭包(惰性思想及应用)

76 阅读1分钟

每次重复兼容性获取,且做判断处理

/**
 * 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]
}
var body = document.body
console.log(getCss(body, 'height'))
console.log(getCss(body, 'margin'))
console.log(getCss(body, 'background'))

重构函数,减少重复兼容性获取,和判断

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'))