1

我在阅读http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml时在带注释的注释的常量部分中注意到:

/**
 * The number of seconds in each of the given units.
 * @type {Object.<number>}
 * @const
 */

然后指南继续说“这允许编译器强制执行常量”。

这是v8的东西吗?这是在哪里记录的?

我的脑海里浮现出这样一种可能性:也许,只是也许,我可以为 v8(或其他)提供类型信息!

4

4 回答 4

7

Google 的Closure Compiler可以接受JSDoc 注释,它会产生警告或错误。

例如,如果您尝试使用Advanced Optimization编译以下代码:

/** @const */ var MY_BEER = 'stout';

MY_BEER = 'bar';

它会产生一个错误:

错误数:1

JSC_CONSTANT_REASSIGNED_VALUE_ERROR:常量 MY_BEER 在第 5 行字符 8 处多次赋值

他们不鼓励使用const关键字,因为它不是 ECMAScript 标准的一部分。

于 2010-08-06T05:09:12.213 回答
3

Javascript 中有一个 const 关键字,但 Internet Explorer 无法识别它,因此您无法真正使用它。

这就是为什么 Google 的 Javascript 样式指南建议使用大写字母作为常量,或者将 @const 放入文档块中。

这两种技术都只是建议性的,对代码没有实际限制。

请注意,当您使用Google 的 Closure Compiler “编译”某些代码时,“编译器”会查看注释块中的此类内容,甚至会生成警告和错误。但这与在实际的 Javascript 解释器中运行未经修改的代码是分开的。

于 2010-08-06T05:10:22.023 回答
0

常量 (MDC)

并且:const (您链接的页面......)

于 2010-08-06T05:02:28.823 回答
0

这个问题有点老了,但是当前版本的 Closure Compiler 可以const很好地处理关键字,因为它只会替换它var并理解变量是常量。

例如,使用高级模式 ( --compilation_level ADVANCED_OPTIMIZATIONS) 和 polyfill 重写 ( --rewrite_polyfills,这很重要,如前所述,“[不要使用]const关键字,因为它不是 ECMAScript 标准的一部分”,但这会重写它var以便它可以很好地播放使用较旧的浏览器)

const get_selected_text = (/** @return {function():string} */ function() {
    if (window.getSelection || document.getSelection) {
        return function () {
            const selection = /** @type {function():Object<string,?>} */ (window.getSelection || document.getSelection)();
            if (typeof selection['text'] === "string") {
                return selection['text'];
            } else {
                return selection.toString();
            }
        };
    } else if (document.selection && document.selection.type !== "Control") {
        return function () {
            return document.selection.createRange().text;
        };
    }
    return function () {
        return '';
    };
})();

出来看起来像

var i=window.getSelection||document.getSelection?function(){var a=(window.getSelection||document.getSelection)();return"string"===typeof a.text?a.text:a.toString()}:document.selection&&"Control"!==document.selection.type?function(){return document.selection.createRange().text}:function(){return""};
于 2018-11-06T18:13:01.857 回答