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

后端 未结 5 1873
既然无缘
既然无缘 2021-01-11 10:43

I have some HTML that contains a JSON string. In the on DOM ready callback, I have something like this:

MyObject = JSON.parse($(\'#TheJsonString\').         


        
相关标签:
5条回答
  • 2021-01-11 11:10

    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);
    
    0 讨论(0)
  • 2021-01-11 11:11

    Try accessing the property in this way:

    var SomeVar = MyObject['MyProp1'];
    
    0 讨论(0)
  • 2021-01-11 11:11

    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.

    0 讨论(0)
  • 2021-01-11 11:19

    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.

    0 讨论(0)
  • 2021-01-11 11:21
    <!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.

    0 讨论(0)
提交回复
热议问题