0

I have a code below and when i try to run get the error when i call the function . I wonder hey this his happening ? help plz ...

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   
                }
        }); 

    });
putvande
  • 15,068
  • 3
  • 34
  • 50
Pradeep Jaiswar
  • 1,785
  • 7
  • 27
  • 48

3 Answers3

6

It's about invoking jq() function before it's declared.

jq is undefined, because it's not declared yet...!

Update (@David Barker suggestion)

The whole code would work if a named function would be declared instead of an anonymous one.

As an anonymous function is created during run-time, it's not available until the assignment is executed.

In opposite, as a named function is declared in parse time, it's available to the code even if it's declared after invoking it.

Example of anonymous function

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

var myFunction = function() {};

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

Example of named function

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

function myFunction() {};

myFunction(); // OK!
Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
3

it should be

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();
    }); 

});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

First you declare a function and then call her because javascript read line by line one after the other, when you call the function jq () it still had not been declared ..

'sorry for my english'