[JS]12.闭包应用(惰性函数)

154 阅读1分钟

惰性函数

  • 能只执行一次的,就不多执行

  • 获取元素样式,得到样式对象

    • window.getComputedStyle([元素对象]) 不兼容ie6-8
    • [元素对象].currentStyle
  • 自己写一个方法,拿到元素的某一个样式,要求兼容所有浏览器

/*
  性能上的问题:
  - 在某个浏览器中渲染页面,每次调用都检测属性没有必要
*/

// element元素对象,需要获得的attr属性
function get_css(element, attr) {
  // 判断是否拥有这个属性
  // if('getComputedStyle' in window) 检测对象中是否有xxx属性
  if(window.getComputedStyle) {    
    return window.getComputedStyle(element)[attr];
  }
  return element.currentStyle[attr];
}

/*
第一次执行get_css就要验证浏览器是否支持getComputedStyle,后面几次调用不需要再验证
*/

var w = get_css(document.body, 'width');
console.log(w);

var h = get_css(document.body, 'height');
console.log(h);
  • 基于惰性思想重构,提高性能

 // 第一次执行,根据浏览器兼容情况,对外部的get_css进行重构

function get_css(element, attr) {
  if('getComputedStyle' in window) {
    // 对外部的get_css进行重构
    // 重写了函数,并未返回
    get_css = function(element, attr) {
      return window.getComputedStyle(element)[attr];
    }
  } else {
    get_css = function(element, attr) {
      return element.currentStyle[attr];
    }
  }
  // import:第一次执行需要获取结果,所以把重构的函数执行一次,返回出去
  return get_css(element, attr)
}