首页 > Web开发 > 详细

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

时间:2016-07-18 02:46:20      阅读:259      评论:0      收藏:0      [点我收藏+]

闭包:

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

  

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

原文:http://www.cnblogs.com/shenggen/p/5679785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!