-2

I have a problem in call a function. My example:

jQuery(function($){
    var testFunc = function(){
        console.info('call jQuery testFunc');
    }
});

function callJqueryTestFunc(){
    testFunc(); // error - function not exists
}

Please, someone help me? Thank you very much

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 4
    Help with what? and if you are to apologise for a lack of English, at least provide some! – ggdx Jan 20 '15 at 09:40
  • 1
    read about js scopes. In your case `testFunc` variable is declared in another, not parent for `callJqueryTestFunc` scope – Kirill Pisarev Jan 20 '15 at 09:40
  • possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Grundy Jan 20 '15 at 09:51

4 Answers4

1

Yes, testFunc() doesn't exist within that context i.e. within the callJqueryTestFunc()

So, you can pass a variable to the function and call that function like this:

var testFunc = function(){
console.info('call jQuery testFunc');
}

});

function callJqueryTestFunc(testFunc){
testFunc(); // now, it exist through closure
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

There is nothing with jQuery. It's javascript scopes. For example

(function(){

    var testFunc = function(){
        console.info('call jQuery testFunc');
    }

}());

function callJqueryTestFunc(){
    testFunc(); // error - function not exists
}

You will get the same error. You cannot access function inside other function

Arūnas Smaliukas
  • 3,231
  • 6
  • 27
  • 46
0

testFunc is in another function (a closure) so is not accessible outside of that function.

If you want it accessible, you can attach it to the window:

jQuery(function($){

    window.testFunc = function(){
        console.info('call jQuery testFunc');
    }

});

function callJqueryTestFunc(){
    testFunc(); // error - function not exists
}
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
0

You need to understand that the function is visible only in scope, where it was created and child scopes. When you have created a function named testFunc inside annonymus jQuery function, then it is visible only inside of it.

You have 2 choces:

  • use window object like so:

    window.testFunc = function(){...}

  • move it outside of your jQuery annonymus function

But remember that you should not pollute global scope with many functions/objects. It's better to have it clean.

Beri
  • 11,470
  • 4
  • 35
  • 57