js 单例模式的实现方式----闭包和构造函数内部判断

闭包:

var singleton = function( fn ){
   var result;
    return function(){
       return result || ( result = fn .apply( this, arguments ) );
    }
}
//test function aa(){} var a = aa() var b = aa() a===b

  

构造函数内部判断

function Construct(){
    // 确保只有单例
    if( Construct.unique !== undefined ){

        return Construct.unique; 

    }
    // 其他代码

    this.name = "Construct";
    Construct.unique = this;

}
//test
var t1 = new Construct() ;
var t2 = new Construct() ;
t1 === t2

  

posted on 2016-07-17 23:49  shenggen  阅读(303)  评论(0编辑  收藏  举报

导航