使用点表示法无法获得价值

时间:2016-04-02 22:16:31

标签: javascript google-closure-compiler google-closure

该代码与WHITESPACE_ONLY选项完美配合。但在ADVANCED模式下,点符号不起作用。但括号表示法仍然可行。

这是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

问题出在哪里?

2 个答案:

答案 0 :(得分:1)

确保understand the differences between the compilation modes

在ADVANCED_OPTIMIZATIONS中,closure-compiler重命名由虚线表示法引用的属性,并且不使用带引号的表示法重命名属性。例如:

<强>原始

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']);

答案 1 :(得分:0)

对于以下行,它返回未定义,因为您从未定义"undefined"。再次检查输出。你读错了。

game

如果将行更改为以下内容,则它将同时用于括号和点表示法:

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

enter image description here