未捕获的类型错误:不是函数,但函数存在


Uncaught TypeError: not a function, but the function exists

我的js文件中有以下内容:

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

现在在我的PHP中,我有:

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

我已经验证了JS正在正确加载到我的页面,我通过相同的PHP页面调用其他JS函数没有问题:

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

但是我现在得到:

Uncaught TypeError: Field_File。ImgLoad不是一个函数

我在这个电话中错过了什么吗?

将你的模块(一个文字对象)的声明改为

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

如果你想要一个作用域来保护一些私有变量,使用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
    }
})();

可能有很多变化,所以重要的是了解这里发生了什么,以便您可以根据自己的需求进行调整。

使用thisImageLoad更改为Field_File的属性。当在这里用var声明它时,你在某种程度上模拟了一个私有属性。

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