简体   繁体   English

JavaScript和常量

[英]JavaScript and Constants

What do you guys think about making constants in Javascript. 你们怎么看待在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')); 我们如何才能全局使用它们(没有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 就在最近,在另一个问题中 ,我深入探讨了如何在node.js中使用全局变量

This is a bad idea, but it can be done. 这是个坏主意,但可以做到。 I've only tested this in Node.js. 我只在Node.js中测试过这个。 It may or may not work in the browser. 它可能在浏览器中有效,也可能无效。 If you substitute global for window it might work reliably in the browser. 如果用global替换window它可能在浏览器中可靠地工作。

Here you go: 干得好:

app.js: 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. 用v0.10.3测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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