douran7929 2015-05-27 15:45 采纳率: 100%
浏览 142
已采纳

未捕获的TypeError:不是函数,但函数存在

I have the following in my js file:

var Field_File = function( _ )
{
    var _objects = null;

    var Init = function( instance, json )
    {
         // load _objects
    }

    var ImgLoad = function( elem, type )
    {
        //do things with _objects
    }
}

Now in my PHP, I've got:

<img id="file_uploader2_button" src="http://localhost/img/icons/up.png" onload="Field_File.ImgLoad(this, 'img');">

I've verified that the JS is loading into my page properly, and I'm calling other JS functions via the same PHP page with no problems:

body onload="Field_File.Init( '1', {$json});"

But I currently get:

Uncaught TypeError: Field_File.ImgLoad is not a function

Am I missing something in this call?

  • 写回答

2条回答 默认 最新

  • donglu4633 2015-05-27 15:46
    关注

    Change the declaration of your module (a literal object) to

    var Field_File = {
        Init: function( instance, json ){
        },
        ImgLoad: function( elem, type ){
            //do things
        }
    }
    

    If you want a scope to protect some private variables, use an IIFE:

    var Field_File = (function(){
        var _objects = null;
        var Init = function( instance, json ){
             // load _objects
        }
    
        var ImgLoad = function( elem, type ){
            //do things with _objects
        }
    
        return {
            Init:Init,
            ImgLoad:ImgLoad
        }
    })();
    

    Many variations are possible, so what is important is to understand what happens here so that you can adapt it to your needs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?