javascript - 无法使用点表示法获取值

标签 javascript google-closure-compiler google-closure

该代码与 WHITESPACE_ONLY 选项完美配合。但在高级模式下,点表示法不起作用。但括号表示法仍然有效。

这是 JSON 对象:

{
    'title' : 'The title',
    'type' : 'SIM',
    'description' : 'Build your own description.',
    'iconclass' : goog.getCssName('img-icons-bs')
}

这是代码:

console.log('this.obj_ = ' + JSON.stringify(this.obj_));
console.log('this.obj_.iconclass = ' + this.obj_.iconclass);
console.log('this.obj_[iconclass] = ' + this.obj_['iconclass']);

输出:

> this.obj_ = {"title":"The title","type":"SIM","description":"Build 
> your own description.","iconclass":"img-icons-r"}
> this.obj_.iconclass = undefined
> this.obj_[iconclass] = img-icons-r

问题出在哪里?

最佳答案

确保您understand the differences between the compilation modes .

在 ADVANCED_OPTIMIZATIONS 中,闭包编译器重命名由点符号引用的属性,并且不使用引号符号重命名属性。示例:

原文:

var foo = {};
foo.bar = foo['bar'] = 47;

已编译

var a = {};
a.b = a.bar = 47;

由于 JSON 对象属性对编译器隐藏,因此您必须始终使用带引号的表示法来访问它们。

// This line is incorrect - the compiler can rename '.iconclass'
console.log('this.obj_.iconclass = ' + this.obj_.iconclass);

// This line is correct - ["iconclass"] is safe from renaming.
console.log('this.obj_[iconclass] = ' + this.obj_['iconclass']);

关于javascript - 无法使用点表示法获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379364/

相关文章:

javascript - jQuery $.ajax() 请求返回空数据

javascript - 无法在 Heroku 上运行 Node.js 应用程序

javascript - Google 关闭外部依赖项

javascript - 警告 - 全局 this 对象的危险使用

javascript - 如何使用 Google Closure 编译器删除未使用的 JavaScript 代码?

javascript - Web 音频 - 静音期间分析仪频率数据不为 0

javascript - 哪种 JavaScript 数据表与 Google 电子表格类似?

javascript - 有什么方法可以逆转 Closure Compiler(或类似的)对代码的影响吗?

javascript - Google Closure 编译器中的共享 Polyfill