7.1 Singleton

The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time.

var obj = {

    myprop: 'my value'

};

var obj2 = {

    myprop: 'my value'

};

obj === obj2; // false

obj == obj2; // false

In JavaScript every time you create an object using the object literal, you’re actually creating a singleton, and there’s no special syntax involved.

7.1.1 Using New

when you use new  to create several objects using the same constructor, you should get only new pointers to the exact same object.

• You can use a global variable to store the instance. This is not recommended because of the general principle that globals are bad. Plus, anyone can overwrite this global variable, even by accident.

• You can cache in a static property of the constructor. Functions in JavaScript are objects,  so  they  can  have  properties.  You  can  have  something  like Universe.instance and cache the object there. This is a nice, clean solution with the only drawback that the instance property is publicly accessible, and code outside of yours might change it, so you lose the instance.

• You can wrap the instance in a closure. This keeps the instance private and not available for modifications outside of your constructor at the expense of an extra closure.

7.1.2 Instance in a Static Property

function Universe() {

    // do we have an existing instance?

    if (typeof Universe.instance  = = = "object") {

        return Universe.instance;

    }

    // proceed as normal

    this.start_time = 0;

    this.bang = "Big";

    // cache

    Universe.instance = this;

    // implicit return:

    // return this;

} 

// testing

var uni = new Universe();

var uni2 = new Universe(); 

uni === uni2; // true

Drawback

Instance is public

7.1.3 Instance in a Closure

// 7.1 Strington - Instance in closure

function Universe() {

    // the cached instance

    var instance = this;

    // proceed as normal

    this.start_time = 0;

    this.bang = "Big";

    // rewrite the constructor

    Universe = function () {

        return instance;

    };

}

Drawback

The rewritten function (in this case the constructor  Universe()) will lose any properties added to it between the moment of initial definition and the redefinition.

// adding to the prototype

Universe.prototype.nothing = true;

var uni = new Universe();

// again adding to the prototype after the initial object is created

Universe.prototype.everything = true;

var uni2 = new Universe();

// only the original prototype was linked to the objects

uni.nothing; // true

uni2.nothing; // true

uni.everything; // undefined

uni2.everything; // undefined

// that sounds right:

uni.constructor.name; // "Universe"

// but that's odd:

uni.constructor === Universe; // false

The reason that uni.constructor is no longer the same as the  Universe() constructor is because  uni.constructor still points to the original constructor, not the redefined one.

// 7.1 Singleton - Advanced Instance in closure

function Universe() {

    // the cached instance

    var instance;

    // rewrite the constructor

    Universe = function Universe() {

        return instance;

    };

    // carry over the prototype properties

    Universe.prototype = this; // this is point to the origin function

    // the instance

    instance = new Universe();    // This is initialized by the origin Universe() constructor.

    instance.constructor = Universe;  // Rewrite the constructor of the instance object.

    // all the functionality

    instance.start_time = 0;

    instance.bang = "Big";

    return instance;

}

// update prototype and create instance

Universe.prototype.nothing = true; // true

var uni = new Universe();

Universe.prototype.everything = true; // true

var uni2 = new Universe();

// it's the same single instance

uni === uni2; // true

// all prototype properties work

// no matter when they were defined

uni.nothing && uni.everything && uni2.nothing && uni2.everything; // true

// the normal properties work

uni.bang; // "Big"

// the constructor points correctly

uni.constructor === Universe; // true
Alternative solution
var Universe;

(function () {

    var instance;

    Universe = function Universe() {

        if (instance) {

            return instance;

        }

        instance = this;

        // all the functionality

        this.start_time = 0;

        this.bang = "Big";

    };

}());
 

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 7.1 Singleton的更多相关文章

  1. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  2. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  3. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  4. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  5. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  6. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  7. JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns

    In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...

  8. JavaScript Patterns 5.9 method() Method

    Advantage Avoid re-created instance method to this inside of the constructor. method() implementatio ...

  9. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

随机推荐

  1. 提高生产性工具 - Model代码生成器(二)

    首先,我想阐述一下我开发这个工具的一个观点. 如果大家做过对日软件的话,很多时候,日方是进行设计的,数据模型是什么样子的,各个字段的类型,需要做什么验证,验证规则,错误信息,都是日方制定的. 外包就是 ...

  2. 鼠标向下滑动加载div

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. 泛函编程(27)-泛函编程模式-Monad Transformer

    经过了一段时间的学习,我们了解了一系列泛函数据类型.我们知道,在所有编程语言中,数据类型是支持软件编程的基础.同样,泛函数据类型Foldable,Monoid,Functor,Applicative, ...

  4. 泛函编程(4)-深入Scala函数类

    既然是泛函编程,多了解一下函数自然是免不了的了: 方法(Method)不等于函数(Function) 方法不是函数但可以转化成函数:可以手工转换或者由编译器(compiler)在适当的情况下自动转换. ...

  5. Android总结篇系列:Android Intent

    Intent在Android中的重要性不言而喻.本文主要总结下Intent使用过程中需要注意的一些问题. 1.隐式Intent AndroidManifest.xml声明时<intent-fil ...

  6. ENVI【非监督分类】

    非监督分类的概念: 非监督分类,又称“聚类分析或者点群分析”.在多光谱图像中搜寻.定义其自然相似光谱集群的过程.它不必对图像地物获取先验知识,仅依靠图像上不同地物光谱信息进行特征提取,在统计特征的差别 ...

  7. git常用命令表

    本文主要是用来记录一些在git管理的项目中常见的场景及其对应的命令,方便自己和他人使用的时候快速查询.如有不对,敬请指正. 查看某个git命令的帮助文档 git help [command] 查看各个 ...

  8. JavaScript_Html5_LocalStorage项目demo

    项目中localStorage实用 项目中h5本地存储的一个小实用,本意使用cookie,但发现chrome调试被禁用,便用了localStorage. 此需求是一贴吧搜索页,在新用户第一次点击搜索框 ...

  9. 使用Unity3D的50个技巧

    使用Unity3D的50个技巧 刚开始学习Unity3D时间不长,在看各种资料.除了官方的手册以外,其他人的经验也是非常有益的.偶尔看到老外这篇文章,觉得还不错,于是翻译过来和大家共享.原文地址:ht ...

  10. VSTO开发,转帖

    http://www.cnblogs.com/oneivan/p/4243574.html