大写字符串类型

时间:2012-09-26 16:40:53

标签: javascript google-closure-compiler

我有一些类似下面的代码用于下载二进制文件。我的目标是将其转换为base64数据URI,同时支持可能不了解ArrayBuffer的旧浏览器。现在,代码似乎运行得很好。

function download (url) {
    'use strict';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var mime = xhr.getResponseHeader('Content-Type');
            var base64;
            if (oldIE) {
                var rawBytes = ieConvert(xhr.responseBody);
                base64 = encodeString64(rawBytes);
            } else if (xhr.response instanceof ArrayBuffer) {
                var payload = new Uint8Array(xhr.response);
                for (var i = 0, buffer = ''; i < payload.length; i++) {
                    buffer += String.fromCharCode(payload[i]);
                }
                base64 = window.btoa(buffer);
            } else if (xhr.response instanceof String) {
                base64 = encodeString64(xhr.response);
            }
            return 'data:' + mime + ';base64,' + base64;
        } else if (xhr.readyState === 4) {
            throw "Failed.";
        }
    };
    xhr.send();
}

我的问题是,当我使用Google Closure Compiler时,我会收到类型警告。显然,这是因为我使用了instanceof String,但是instanceof string不起作用,因为对象名称应该大写。

WARNING - actual parameter 1 of encodeString64 does not match formal parameter
found   : String
required: string
                    base64 = encodeString64(xhr.response);
                                            ^
0 error(s), 1 warning(s), 85.22012578616352 typed

知道如何摆脱这种警告吗?

1 个答案:

答案 0 :(得分:2)

base64 = encodeString64(String(xhr.response));

尝试这一点以了解其中的差异:

<script>
x = new String("hello");
alert(typeof x); //prints Object (this is a String object)

x = String("hello"); //or x = "hello";
alert(typeof x); //prints string (this is string with small s - similar to running toString() on a JS object)
</script>