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

JavaScript05

如何优雅的创建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后,再进一步修改属性值)。

for...in每次循环中的value并不是同一个value,

for(const value in iterable){

console.log(value)

}

相当于每次都用const重新定义了一个新的value存储iterable中的值,并打印到控制台上;

如果你这样写就会报错,告知你const不可以修改

const value = 1//const定义常量必须有默认值

for(value in iterable){

}