Search code examples
javascriptgoogle-closure-compilerjsdoc

How do I annotate my usage of "this" to the Closure Compiler in the following Javascript function?


I am using the following function to modify the behavior of a specific instance of a Javascript array. How can I annotate the code for Closure Compiler? http://code.google.com/closure/compiler/docs/js-for-compiler.html Running the code through the compiler produces a "JSC_USED_GLOBAL_THIS" error.

function listify(array) {
    array.toString = function() {
        return '[' + this.join(', ') + ']';
    };
    return array;
};

It doesn't look like I can use the @extends or @constructor annotation.

I do not want to modify the global Array prototype because that would have unintended side effects when other code is used on the page. Also, after reading http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/ , I think my approach is the best one for my use case. The problem is I just don't know how to annotate it to the Compiler


Solution

  • function listify(array) {
    
        /**
         * Returns the roster widget element.
         * @this {Array}
         * @return {String}
         */
        array.toString = function() {
            return '[' + this.join(', ') + ']';
        };
        return array;
    };