---
title: "JS单例模式"
author: "topcss"
date: "2011-07-06T16:10:36Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2011-07-07T11:30:57Z"
id: 1117110
url: "https://topcss.iteye.com/blog/1117110"
---

```
<!DOCTYPE HTML>
<html>
	<head>
		<script type="text/javascript">
			var MyNamespace = {};
			MyNamespace.singleton = (function(){
				var uniqueInstance;
				function constructor(){
					var fields;
					
					this.setFields = function(Too){
						fields = Too;
					};
					this.getFields = function(){
						return fields;
					}
				};
				return {
					getInstance : function(){
						if(!uniqueInstance){
							uniqueInstance = new constructor();
						}
						return uniqueInstance;
					}
				};
			})();
			
			var NSG = MyNamespace.singleton.getInstance();
			
			NSG.setFields("AAA");
			alert(NSG.getFields());
			
		</script>
	</head>
</html>
```