0

我在下面有一个代码,当我尝试运行时,当我调用该函数时会出现错误。我想知道,嘿,这是他发生的事情吗?帮助请...

jQuery(document).ready(function($) {
        //load config file 
        $.getScript(baseURl+"/wsj/wconf.js", function(data, textStatus, jqxhr) {
            console.log(data); // it is ok 

                jq();  // Uncaught TypeError: undefined is not a function 
                //_cusApp.ini();  //Uncaught TypeError: Cannot call method 'ini' of undefined 

                var _cusApp = {
                        ini: function (inc) {
                            console.log('ini'); 
                        },
                };

                var jq = function ( ){
                    $(document).height(); // jquery not availble here   
                }
        }); 

    });
4

3 回答 3

6

这是关于在声明之前调用jq()函数。

jq是未定义的,因为它还没有被声明......!

更新(@David Barker 建议)

如果声明一个命名函数而不是匿名函数,则整个代码都可以工作。

由于匿名函数是在运行时创建的,因此在执行分配之前它不可用。

相反,由于命名函数是在解析时声明的,因此即使它是在调用它之后声明的,它也可用于代码。

匿名函数示例

myFunction(); // Wrong, it's undefined!

var myFunction = function() {};

myFunction(); // OK, now is declared and it can be invoked

命名函数示例

myFunction(); // As the function has been already parsed, it is available!

function myFunction() {};

myFunction(); // OK!
于 2013-08-09T11:26:00.337 回答
3

它应该是

jQuery(function($) {
    //load config file 
    $.getScript(baseURl+"/wsj/wconf.js", function(data, textStatus, jqxhr) {
        console.log(data); // it is ok 

        //these two variable declaration shoule happen before their usage
        var _cusApp = {
            ini: function (inc) {
                console.log('ini'); 
            },
        };

        var jq = function ( ){
            $(document).height(); // jquery not availble here   
        }

        jq();
        _cusApp.ini();
    }); 

});
于 2013-08-09T11:25:09.690 回答
0

首先你声明一个函数,然后调用她,因为javascript逐行读取,当你调用函数jq()时它仍然没有被声明..

'对不起我的英语不好'

于 2013-08-09T13:07:50.327 回答