如何优雅的创建nodejs共享常量

JavaScript013

如何优雅的创建nodejs共享常量,第1张

1. 用global来保存常量

const.js

global.MY_CONST= 'global const'11

技术上可以,你只需要 require const.js,无需保存返回值

main.js

require('./const')

console.log(global.MY_CONST)

global.MY_CONST = 'changed global const'

console.log(global.MY_CONST)12341234

但是设计原则上来讲,应该将内容封装到文件内,通过exports导出。

而且,这种方式并不能定义常量。

2. 直接export一个包含常量的对象

const.js

const obj = {

MY_CONST:'my const'

}

module.exports = obj

123456123456

这种方式有同样的问题,const并不能定义一个属性无法修改的对象,MY_CONST依然是可以修改的。

3. 用Object.defineProperty来定义常量

上面的方法试图定义一个const对象,但这是不可能的。但是我们可以通过配置将对象属性的设定为不可修改的。

const.js

Object.defineProperty(exports, "PI", {

value:3.14,

enumerable: true,

writable: false,

configurable: false

})123456123456

writable和configurable默认是false,所以可以简化一下

Object.defineProperty(exports, "PI", {

value:3.14,

enumerable:true

})12341234

更好的方式,如果你不想为每一个属性都手写配置的话:

function define(name, value) {

Object.defineProperty(exports, name, {

value: value,

enumerable: true

})

}

define("PI", 3.14)1234567812345678

看起来更舒服了。

4. 通过 Object.freeze 来固定属性值

const.js

module.exports = Object.freeze({

MY_CONSTANT: 'some value',

ANOTHER_CONSTANT: 'another value'

})12341234

freeze的简单介绍,来自 mozilla:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to itprevents existing properties from being removedand prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

大概意思是说,freeze能够阻止对象属性的添加,删除,以及属性的enumerable, writable,configurable的修改,也就是将此对象变成一个不可变对象。

想必前一种方案,这种更简单,更安全(因为阻止了对属性writable的修改,所以也不担心某些别有用心的人修改了常量的writable后,再进一步修改属性值)。

1. 定义一些常量,使用闭包,匿名函数实现常量的定义。

例如:

var Class = (function() {

var UPPER_BOUND = 100//定义了常量

var Test={}

// 定义了一个静态方法 获取常量的方法

Test.getUPPER_BOUND=function() {

return UPPER_BOUND

}

return Test

})()

用法:

var k=Class.getUPPER_BOUND()

alert(k)//

2.多个常量的情况下:

var Class = (function() {

// Private static attributes.

var constants = {//定义了两个常量

UPPER_BOUND: 100,

LOWER_BOUND: -100

}

var Test={}

// 定义了一个静态方法

Test.getConstant=function(name){//获取常量的方法

return constants[name]

}

return Test

})()

用法:

var k=Class.getConstant('UPPER_BOUND')

alert(k)