jjzjj

javascript - 如何防止警告 'Property MyProp1 never defined on MyObject' ?

coder 2024-05-09 原文

我有一些包含 JSON 字符串的 HTML。在 DOM 就绪回调中,我有这样的东西:

MyObject = JSON.parse($('#TheJsonString').html());

稍后在我的代码中,我写了一些这样的东西:

var SomeVar = MyObject.MyProp1;

然后当我通过 Google 闭包编译器运行代码时,我收到了警告

Property MyProp1 never defined on MyObject.

应该如何编写代码才不会产生警告?

最佳答案

消除警告的最简洁方法是定义 JSON 的结构。这可以使用 @type 标签来完成:

/** @type {{MyProp1:string}} */

其中 MyProp1 是属性的名称,string 是类型。

Google 的 Closure 编译器将重命名该变量。如果你不想这样,你必须使用引号 + 括号而不是点符号:

MyObject['MyProp1']

示例:将以下内容粘贴到 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);

关于javascript - 如何防止警告 'Property MyProp1 never defined on MyObject' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9561138/

有关javascript - 如何防止警告 'Property MyProp1 never defined on MyObject' ?的更多相关文章

随机推荐