(转) 惰性加载
04 January 2018
原文: JavaScript 专题之惰性函数
function foo() {
  if (foo.t) {
    return foo.t;
  }
  foo.t = new Date();
  return foo.t;
}

console.log(foo()); // 2018-01-04T02:42:38.371Z
console.log(foo()); // 2018-01-04T02:42:38.371Z
console.log(foo()); // 2018-01-04T02:42:38.371Z



var foo = function() {
  var t = new Date();
  return (function() {
    return t;
  })();
};

console.log(foo()); // 2018-01-04T02:42:38.371Z
console.log(foo()); // 2018-01-04T02:42:38.371Z
console.log(foo()); // 2018-01-04T02:42:38.371Z

另一个例子

var addEvent = (function(){
  if (window.addEventListener) {
    return function (type, el, fn) {
      el.addEventListener(type, fn, false);
    }
  }
  else if(window.attachEvent){
    return function (type, el, fn) {
      el.attachEvent('on' + type, fn);
    }
  }
})();


function addEvent (type, el, fn) {
  if (window.addEventListener) {
    addEvent = function (type, el, fn) {
      el.addEventListener(type, fn, false);
    }
  }
  else if(window.attachEvent){
    addEvent = function (type, el, fn) {
      el.attachEvent('on' + type, fn);
    }
  }
}

当我们每次都需要进行条件判断,其实只需要判断一次,接下来的使用方式都不会发生改变的时候,想想是否可以考虑使用惰性函数