如何防止警告'属性MyProp1从未在MyObject上定义'? [英] How can I prevent the warning 'Property MyProp1 never defined on MyObject'?
问题描述
我有一些包含JSON字符串的HTML。在 on DOM ready 回调中,我有类似这样的内容:
I have some HTML that contains a JSON string. In the on DOM ready callback, I have something like this:
MyObject = JSON.parse($('#TheJsonString').html());
稍后在我的代码中,我写了一些内容:
Later in my code, I write something this:
var SomeVar = MyObject.MyProp1;
然后当我通过Google闭包编译器运行代码时,我收到警告
And then when I run the code through the Google closure compiler, I get the warning
属性MyProp1从未在MyObject上定义。
Property MyProp1 never defined on MyObject.
应该如何编写代码,以便它不会产生警告?
How should the code be written so that it doesn't generate a warning?
推荐答案
删除警告的最简洁方法是定义JSON的结构。这可以使用 @来完成键入
标记:
The cleanest way to remove the warning is by defining the structure of the JSON. This can be done using the @type
tag:
/** @type {{MyProp1:string}} */
其中 MyProp1
是属性和字符串
是类型。
Google的Closure编译器将重命名该变量。如果你不想这样,你必须使用引号+括号而不是点符号:
Google's Closure compiler will rename the variable. If you don't want that, you have to use quotes + brackets instead of the dot-notation:
MyObject['MyProp1']
示例:将以下内容粘贴到关闭编译器:
Example: paste the following in the Closure Compiler:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
var MyObject;
function x() { // Magic happens at the next line
/** @type {{MyProp1:string}}*/
MyObject = JSON.parse(prompt(''));
}
function afterX() {
var SomeVar = MyObject.MyProp1;
alert(SomeVar);
}
x();
afterX();
输出:
var a;a=JSON.parse(prompt(""));alert(a.a);
这篇关于如何防止警告'属性MyProp1从未在MyObject上定义'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!