douran7929
2015-05-27 15:45 阅读 107

未捕获的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 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.

    点赞 评论 复制链接分享
  • dougangxin5695 dougangxin5695 2015-05-27 15:51

    Change ImageLoad to a property of Field_File using this. When declaring it with var here, you are somewhat simulating a private property.

    var Field_File = function( _ )
        this.Init = function( instance, json )
        {
        }
    
        this.ImgLoad = function( elem, type )
        {
            //do things
        }
    }
    
    点赞 评论 复制链接分享

相关推荐