javascript 单例模式详解及简单实例

JS 单例模式

概要:

单例指一个类只有一个实例,这个类自行创建这个实例。

利用对象字面量直接生成一个单例:

rush:js;"> var singleton = { prop: 1,method: function(){ console.log(a); //1 } }

严格的说对象字面量可能不算单例模式,生成单例是对象字面量的作用(已经被封装),而单例模式是一个设计模式(需要自行构思或设计)。

在类内部用new生成实例的单例模式:

rush:js;"> var instance; var foo = function(){ if(!instance){ instance = new Singleton(); } return instance; function Singleton(){ this.name = 'single'; this.method = function(){ console.log(this.name); } }; }

var a = foo();
var b = foo();
a.method(); //single
console.log(a === b); //true

单例模式只要检测一个实例是否被生成。假如没有实例,则生成实例。假如已经生成则返回这个实例。保证这个类只有这一个实例。

由于hoisting,函数会提前声明,所以 singleton 函数放在哪都没所谓,但是每次调用都会声明函数singleton,可能会不够优雅。

由于new关键字是执行函数,同时this指向这个对象,所以可以判断类的this是否赋值给instance:

rush:js;"> var instance; var Singleton = function(){ if(instance){ return instance; } instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); } }

var a = new Singleton();
var b = new Singleton();
a.method(); //single
console.log(a === b); //true

这个例子中,把instance指向了Singleton这个类,然后在类外部通过new来实例化,和上例中的new异曲同工。由于是通过修改this来达到检测是否执行过Singleton类,所以个人感觉不够语义化。

上面的例子用es6重构的写法。

类内部new生成单例:

rush:js;"> var instance; class foo{ static Singleton(){ if(!instance){ instance = new foo(); } return instance; } method(){ this.name = 'single'; console.log(this.name); } }

var a = foo.Singleton();
var b = foo.Singleton();
a.method(); //single
console.log(a === b); //true

修改this指向生成单例:

rush:js;"> var instance; class foo{ constructor(){ if(!instance){ this.Singleton(); } return instance; } Singleton(){ instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); } } }

var a = new foo();
var b = new foo();
a.method(); //single
console.log(a === b); //true
  

当然除了这两种以外还有别的方式能实例化一个单例。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...