有没有办法在JavaScript中使用常量?
如果没有,指定用作常量的变量的常见做法是什么?
Eclipse为以下代码的第4行提供了"Missing decmicolon"警告:
const C = 'b';
function foo() {
alert('x');
}
Run Code Online (Sandbox Code Playgroud)
它不适用于以下代码:
//const C = 'b';
function foo() {
alert('x');
}
Run Code Online (Sandbox Code Playgroud)
对于以下内容,它给了我两个警告:
const C = 'b';
function foo() {
alert('x');
};
Run Code Online (Sandbox Code Playgroud)
此行有多个标记
有没有办法让Eclipse用'const'忽略我的行?或者有另一种方法可以解决我的问题吗?
我在用:
用于JavaScript Web开发人员的Eclipse IDE.
版本:Indigo Service Release 1
Build id:20110916-0149
现在内置于PhpStorm的JSHint检查告诉了我关于JavaScript魔术数字的信息,并且我意识到这将使更清晰的代码避免使用它们.
我试过这个:
var constants = {
millisecs: 1000,
secs: 60
};
Run Code Online (Sandbox Code Playgroud)
还有这个:
var constants = function () {
this.millisecs = 1000;
this.getMillisecs = function () {
return this.millisecs;
};
};
Run Code Online (Sandbox Code Playgroud)
JsHint抱怨两者.
从这个答案中解决方案虽然运行正常:
var constants = (function() {
var millisecs = 1000,
defaultMsgsPerSecond = 60;
this.getMillisecs = function() { return millisecs; };
this.getDefaultMsgsPerSecond = function() { return defaultMsgsPerSecond; };
})();
Run Code Online (Sandbox Code Playgroud)
大概是因为关闭.为什么这是被接受的,而从另一个SO问题中提出的另外两个建议却不是?
编辑:虽然没有触发错误,但实际上并不起作用.如果说常量未定义则错误.JsFiddle.
澄清 - 通过"作品"我的意思是"不会触发JsHint的警告"