How can I prevent the warning 'Property MyProp1 never defined on MyObject'?

戏子无情 提交于 2019-12-03 23:55:18

问题


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;

And then when I run the code through the Google closure compiler, I get the warning

Property MyProp1 never defined on MyObject.

How should the code be written so that it doesn't generate a warning?


回答1:


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}} */

Where MyProp1 is the name of the property, and string is the type.

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();

Output:

var a;a=JSON.parse(prompt(""));alert(a.a);



回答2:


To suppress this warning for a specific function, you can use the @suppress annotation:

/**
 * @suppress {missingProperties}
 */
function useJsonObject() { ... }

To turn off this warning globally, use the jscomp_off compiler flag to turn off the missingProperties class of warnings.




回答3:


Try accessing the property in this way:

var SomeVar = MyObject['MyProp1'];



回答4:


Instead of putting the JSON content in the #TheJsonString object as HTML, you should put it in your page as actual javascript. If the server is generating the content in the page, then there's no reason that the server needs to generate HTML which you then parse. The server can just make a javascript variable inside a script tag and put the actual javascript data structure in it.

JSON.parse() is very useful for parsing ajax responses, but it really isn't needed when the server can just put the finished javascript right in the generated page in the first place.




回答5:


<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="TheJsonString">
    {"bindings": "hr", "method":"asd"}
</div>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
    var MyObject = JSON.parse($('#TheJsonString').html());

    var SomeVar = MyObject.bindings;

    console.log(SomeVar);
</script>
</body>
</html>

I tested it like this, but it works fine without any warnings.



来源:https://stackoverflow.com/questions/9561138/how-can-i-prevent-the-warning-property-myprop1-never-defined-on-myobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!