Search code examples
javascript

javascript: object is not a function


I write a module:

window.FileReader = (function () {

        var read = function (file) {
            var reader = new FileReader();

            reader.onload = function (e) {
                console.log(e.target);
            };

            // reader.readAsDataURL(file);
        };

        return {
            read: read
        };
    })();

but when I execute

FileReader.read()

it always warn me object is not function at var reader = new FileReader()

what's wrong with my code?


Solution

  • It's saying that because you've made FileReader not a function, you've replaced it with an object (which has a function called read). All globals are properties of the global object (window, on browsers), so by setting window.FileReader = { ... };, you're replacing the global FileReader function with your object.

    You seem to be trying to use the File API. That being the case, you want to not call your global module object FileReader, as that's defined by the File API. Call it something more specific to you (here I'm using Foo as an obviously-nonsense example):

    window.Foo = (function () {
    
        var read = function (file) {
            var reader = new FileReader();
    
            reader.onload = function (e) {
                console.log(e.target);
            };
    
            // reader.readAsDataURL(file);
        };
    
        return {
            read: read
        };
    })();
    
    // Usage:
    Foo.read();