<script type="text/javascript">
var Singleton = function() {
var _instance = null;
return {
getInstance : function() {
if (!_instance) {
_instance = ['a', 'b', 'c', 'd'];
}
return _instance;
}
}
}();
document.write(Singleton.getInstance());
</script>
保证只有一个实例对象,并且提供一个方法可让全局访问到此实例对象。
一些应用场景:
某些JavaScript的UI组件中,需要获取页面的DOM对象,只需要调用getInstance方法时返回该实例(调用时才判断是否已被初始化)的引用即可。
实际中的应用如一个Dialog框:alert型、confirm型、loading型、login型..,可能只在需要创建一次容器(为避免频繁对DOM树的修改引发DOM的reflow而导致的消耗系统资源或是产生内存泄露)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>单例模式</title>
<meta name="generator" content="editplus" />
<meta name="author" content="meteoric_cry" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
.tip {
background-color:#68af02;padding:5px 14px;color:#fff; font-size:14px;position:absolute;
}
</style>
</head>
<body>
<button onclick="Dialog.getInstance().update('111111');">显示框</button>
<button onclick="Dialog.getInstance().update('内容已被修改');">修改内容</button>
<script type="text/javascript">
var Dialog = function() {
var inner;
var _instance = null;
return inner = {
getInstance : function() {
if (!_instance) {
_instance = document.createElement("div");
_instance.className = "tip";
document.body.appendChild(_instance);
}
return inner;
},
update : function(str) {
_instance.innerHTML = str;
}
}
}();
</script>
</body>
</html>