zoukankan      html  css  js  c++  java
  • js设计模式之单例模式

    废话不多说,直接上代码以供参考吧!

     1 var SingleInstanceTest = (function () {
     2   var _instance = null;    //  申明一个唯一的对象
     3   //  设置默认值
     4   var _default = { name: '无名氏',age: 18 };
     5   function SingleInstance(ops) {
     6     if (this instanceof SingleInstance) {   //  优化处理不使用new关键字的问题
     7       if(_instance == null){   // 每次实例化判断对象是否为空
     8         this._init(ops);
     9         return _instance = this;
    10       }else{
    11         _instance._init(ops);
    12         return _instance;       
    13       }
    14     }else{
    15       if (!_instance) {
    16         _instance = new SingleInstance();
    17         _instance._init(ops);
    18         return _instance;
    19       } else {
    20         _instance._init(ops);
    21         return _instance;
    22       }
    23     }
    24   }
    25 
    26   SingleInstance.prototype._init = function (ops) {
    27     //  如果传进来的数据为真,则复制给默认数据
    28     for(var prop in ops){
    29       if(ops[prop]){
    30         _default[prop] = ops[prop];
    31       }
    32     }
    33     //  如果传进来的数据不包含默认数据中的字段,则将默认数据中的字段填充进传进来的对象中
    34     for(var prop in _default){
    35       this[prop] = _default[prop];
    36     }
    37   }
    38   return SingleInstance;
    39 })()
    40 
    41 var i0 = SingleInstanceTest({ name: '王五' });
    42 var i1 = new SingleInstanceTest({ name: '张三', age: 20 })
    43 var i2 = new SingleInstanceTest({ name: '李四' })

     再举一个显示与影藏div功能的单例

    var Popup = (function() {
      var div = document.createElement('div');
      document.body.appendChild(div);
      var _instance = null;     //  创建一个唯一的对象
      return function () {
        if (_instance == null){   //  每次实例化判断_instance是否为空
          _instance = new Object();
    
          _instance.hide = function () {
            div.style.display = 'none';
          }
          _instance.show = function () {
            div.style.display = 'block';
          }
        }
        return _instance;
      }
    })()
  • 相关阅读:
    数据库表结构变动发邮件脚本
    .net程序打包部署
    无法登陆GitHub解决方法
    netbeans 打包生成 jar
    第一次值班
    RHEL6 纯命令行文本界面下安装桌面
    C语言中格式化输出,四舍五入类型问题
    I'm up to my ears
    How to boot ubuntu in text mode instead of graphical(X) mode
    the IP routing table under linux@school
  • 原文地址:https://www.cnblogs.com/cscredis/p/9289473.html
Copyright © 2011-2022 走看看