8

JSHint 的检查现在内置在 PhpStorm 中,让我了解了 JavaScript 幻数,我意识到这将使代码更清晰,从而避免使用它们。

我试过这个:

var constants = {
    millisecs: 1000,
    secs: 60
};

还有这个:

var constants = function () {
    this.millisecs = 1000;
    this.getMillisecs = function () {
        return this.millisecs;
    };
};

JsHint 抱怨两者。

这个答案中获取解决方案虽然效果很好:

var constants = (function() {
    var millisecs = 1000,
        defaultMsgsPerSecond = 60;
    this.getMillisecs = function() { return millisecs; };
    this.getDefaultMsgsPerSecond = function() { return defaultMsgsPerSecond; };
})();

估计是关门的缘故。为什么这被接受了,而从另一个 SO 问题中得到的其他两个建议却没有?

编辑:虽然没有触发错误,但它实际上不起作用。说常量未定义是错误的。提琴手

澄清一下——“作品”是指“不会触发来自 JsHint 的警告”

4

2 回答 2

6

在 EcmaScript 6 中,您将能够:

const MILLISECS = 1000;
const DEFAULT_MSG_PER_SECOND = 60;

但在那之前,您可以使用 EcmaScript 5 的 Object.freeze:

var constants = {
  millisecs: 1000,
  defaultMsgPerSecond: 60
};

var constants = Object.freeze(constants);

// Now constants is in fact... a constant!
constants.millisecs = 999;
constants.millisecs; // Still === 1000

如果你的天性是冗长,你可以试试 Object.defineProperties:

var constants = {};

Object.defineProperties(constants, {
    'millisecs': {
        value: 1000,
        writable: false
     },
    'defaultMsgPerSecond': {
        value: 60,
        writable: false
     },
});

// Again, constants is in fact... a constant!
constants.millisecs = 999;
constants.millisecs; // Still === 1000
于 2014-07-07T17:33:45.050 回答
4

关于你的编辑

我想你想要new内联对象:

var constants = new (function() {
    var millisecs = 1000,
        defaultMsgsPerSecond = 60;
    this.getMillisecs = function() { return millisecs; };
    this.getDefaultMsgsPerSecond = function() { return defaultMsgsPerSecond; };
})();

但是JSHint 也会抱怨:Weird construction. Is 'new' unnecessary?.

如果你把它用作闭包,那么你实际上需要返回一些东西。如果不这样做,constants确实会包含undefined. 一个简单的解决方法是 return this,但这将是一个糟糕的解决方案,因为您正在扩展this它是您不拥有的对象的实例。

所以返回一个内联对象似乎是这里的解决方案:

var constants = (function() {
    var millisecs = 1000,
        defaultMsgsPerSecond = 60;
    return {
        getMillisecs: function() { return millisecs; }
        getDefaultMsgsPerSecond: function() { return defaultMsgsPerSecond; }
    };
})();
于 2013-10-30T19:01:17.477 回答