zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    idea
    C#
    mysql
    .net5
    .net5
    .net5
    .net5
    .net5
    .net5
    .net5
  • 原文地址:https://www.cnblogs.com/shenggen/p/5679785.html
Copyright © 2011-2022 走看看