简体   繁体   中英

JavaScript and Constants

What do you guys think about making constants in Javascript. I want to do it in the best possible way. I know that constants do not really exist but I wrote this and I was not able to change the values after the export.

Is there a need for constants?

Is there a work around?

How can we use them global (without require('const')); ?

// Const
var constants = {
    'PATH1' : __dirname + '/path..../',
    'PATH2' : __dirname + '/path/..../'
};
module.exports = function(key) {
    return constants[key];
};
//console.log(constants('PATH1'));

Would be glad if I get some feedback, like your thoughts about these questions.

I wish you a good day.

It's ugly/difficult to use globals in node for a good reason: globals are bad.

Doing what you want is as easy as:

// config.json
module.exports = {
  somePath:    "/foo",
  anotherPath: "/foo/bar"
};

Use in a file

// a.js
var config = require("./config");
config.somePath; //=> "/foo"

Use in another file

// b.js
var config = require("./config");
config.anotherPath; //=> "/foo/bar"

Just recently, in another question , I went into depth about how it's completely unnecessary to use globals in node.js

This is a bad idea, but it can be done. I've only tested this in Node.js. It may or may not work in the browser. If you substitute global for window it might work reliably in the browser.

Here you go:

app.js:

Object.defineProperty(global, 'myConst', {
  get: function() {
    return 5;
  }
})

myConst = 6

console.log(myConst) //5

Run like:

node app.js

Tested with v0.10.3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM