首页 > 代码库 > js 单例模式笔记

js 单例模式笔记

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

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

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

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

 

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

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:

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类,所以个人感觉不够语义化。

 

js 单例模式笔记