Home > Web Front-end > JS Tutorial > body text

js单例模式的两种方案_javascript技巧

WBOY
Release: 2016-05-16 17:19:18
Original
1002 people have browsed it

方案一:利用闭包的两个作用,可以变通地读到内部的变量,二是可以让这些变量始终在内存中。

复制代码 代码如下:

//方案一
    var SingletonTester = (function () {
        //单例方法
        function Singleton(args) {
            var args = args || {};
            this.name = 'SingletonTester'; //方法对外的属性,另外一种方式就是返回对象
            this.pointX = args.pointX || 6;
            this.pointY = args.pointY || 10;
        }

        //单例实例
        var instance;

        //返回对象
        return {
            name: 'SingletonTester',

            getInstance: function (args) {
                if (instance === undefined) {
                    instance = new Singleton(args);
                }
                return instance;
            }
        };
    })(); //直接执行该方法

    //测试
    var test = SingletonTester.getInstance({ pointX: 5 });
    console.log(test.pointX);

方案二: 

复制代码 代码如下:

//方案二
  function Universe() {
      // 判断是否存在实例
      if (typeof Universe.instance === 'object') {
          return Universe.instance;
      }

      // 其它内容
      this.start_time = 0;
      this.bang = "Big";

      // 缓存
      Universe.instance = this;

      // 隐式返回this
  }

  // 测试
  var uni = new Universe();
  var uni2 = new Universe();
  console.log(uni === uni2); // true

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!