首页 > 代码库 > 惰性单例

惰性单例

var getSingle=function(fn){
  var result;
  return function(){
    return result || ( result= fn.apply(this,arguments) );
  };
};

 传入函数执行一次

var createLoginLayer = function(){
  var div = document.createElement( ‘div‘ );
  div.innerHTML = ‘我是登录浮窗‘;
  div.style.display = ‘none‘;
  document.body.appendChild( div );
  return div;
};

var createSingleLoginLayer = getSingle( createLoginLayer );
document.getElementById( ‘loginBtn‘ ).onclick = function(){
  var loginLayer = createSingleLoginLayer();
  loginLayer.style.display = ‘block‘;
};

 

 

 摘自JavaScript设计模式与开发实践

惰性单例