单例模式
单例模式的定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式是一种常用的模式,有一些对象我们只需要一个,比如线程池、全局缓存、浏览器中的windows对象等。在JavaScript开发中,单例模式的用途同样非常广泛。比如当我们单击登录按钮时,页面中会出现一个登录浮窗,而这个登录浮窗是唯一的,无论单击多少次登录按钮,这个浮窗只会被创建一次,那么这个登录浮窗就适合用单例模式来创建。
单例模式实现
function Test(name){
if(typeof Test.intance === 'object'){
return Test.intance;
}
this.name = name;
Test.intance = this;
}
const a = new Test('one');
// Test.intance = {}; 问题:外部可更改此变量
const b = new Test();
console.log(a === b); // true
function Test(name){
let instance = this;
this.name = name;
Test = function(){
return instance;
}
}
const a = new Test();
// Test.prototype.lastName='h'; 问题:两个对象并不是同一个构造函数创建
const b = new Test();
console.log(a === b,b.lastName); // true undefined
const Test = (function(){
let instance;
return function(name){
if(typeof instance === 'object'){
return instance;
}
this.name = name;
instance = this;
}
})()
const a = new Test();
Test.prototype.lastName = 'h';
const b = new Test();
console.log(a === b,b.lastName); // true h
单例模式高级使用,让普通函数变成单例模式
const getSingle = function(func){
let result;
return function(){
if(!result){
result = func.apply(this,arguments);
}
return result;
}
}