JavaScript Patterns 7.1 Singleton
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的更多相关文章
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
- JavaScript Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- JavaScript Patterns 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
- JavaScript Patterns 6.3 Klass
Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...
- JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance
// the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...
- 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 ...
- JavaScript Patterns 5.9 method() Method
Advantage Avoid re-created instance method to this inside of the constructor. method() implementatio ...
- JavaScript Patterns 5.8 Chaining Pattern
Chaining Pattern - Call methods on an object one after the other without assigning the return values ...
随机推荐
- Java连接MYSQL 数据库的连接步骤
这篇文章主要以MySQL为例讲下Java如何连接到数据库的. 当然,首先要安装有JDK(一般是JDK1.5.X).然后安装MySQL,这些都比较简单,具体过程就不说了.配置好这两个环境后,下载JDBC ...
- C#编程总结(五)多线程带给我们的一些思考
C#编程总结(五)多线程带给我们的一些思考 如有不妥之处,欢迎批评指正. 1.什么时候使用多线程? 这个问题,对于系统架构师.设计者.程序员,都是首先要面对的一个问题. 在什么时候使用多线程技术? 在 ...
- 速战速决 (2) - PHP: 数据类型 bool, int, float, string, object, array
[源码下载] 速战速决 (2) - PHP: 数据类型 bool, int, float, string, object, array 作者:webabcd 介绍速战速决 之 PHP 数据类型 boo ...
- Ajax中传递Json格式的参数
$.ajax({ type: "post", url: baseUrl+"sys/login", dataType: "json", con ...
- 对Java并发编程的几点思考
1. Threads 和 Runnables 所有的现代操作系统都通过进程和线程来支持并发.进程是通常彼此独立运行的程序的实例,比如,如果你启动了一个Java程序,操作系统产生一个新的进程,与其他程序 ...
- ecshop适应PHP7的修改
说实话,ecshop这个系统,到目前也没见怎么推出新版本,如果是新项目,不太建议使用它.不过,因为我一直以来都在使用中,所以不得不更改让其适应PHP新版本.现在PHP 7已经出发行版了,所以更改来继续 ...
- jQuery Sidebar 侧边栏
在线实例 左边栏 右边栏 使用方法 <div class="txt"> <p class="btn"> ...
- Semantic UI – 完全语义化的前端界面开发框架
Semantic UI 是一个 UI 库,使前端开发更简单,更容易学习.Semantic UI 介绍了许多界面元素.在大多数情况下,只有你需要的元素建立一个自定义的构建可能是最好的. UI 组件分为四 ...
- MyEclipse之无法连接到MySQL数据库
问题描述: 在连接mysql中出现如下警告 Fri Oct 28 02:21:53 CST 2016 WARN: Establishing SSL connection without server' ...
- [deviceone开发]-仿微信主界面示例
一.简介 模仿微信主界面的4个页面,作为一个很常规应用的框架模板,值得参考.另外包括简单的菜单,其中搜索还支持语音录入,不过你需要增加飞讯的语音组件重新打包,才能看到效果 二.效果图 三.相关下载 h ...