---
title: "Javascript 的函数式对象（六）利用闭包模拟静态常量"
author: "hbc8848"
date: "2010-11-03T00:50:40Z"
tags: ["JavaScript"]
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2010-11-03T10:16:57Z"
id: 801221
url: "https://hbc8848.iteye.com/blog/801221"
---

js的闭包特性，还可用来模拟java中的final静态常量，

 

这些常量在定义时被赋值，可被外部访问，但不能被修改。

 

 

```
// 这个Constant类用来保存应用中的所有final静态常量
var Constant = (function(){
	//不可被外部访问的闭包私有静态变量
	var constants = {
		VERSION: 7.5
	};
	
	//构造函数
	var constructor = function(){};
	
	//可被外部访问，也可访问闭包内私有静态变量的方法
	constructor.getConstants = function(name){
		return constants[name];
	};
	
	return constructor;	
})();

//访问Constant闭包中的静态常量
Constant.getConstants('VERSION'); // return 7.5
```

 

 

上述“final静态常量”，是借用面向对象语言的概念，有助理解。

 

当Constant被设为null后，闭包内的变量仍将被回收。