0

I have this code:

(function ($) {  

    $(document).ready(function() { 
         test("hola","caracola");
    });

    function test(somevar1, somevar2)
    {
        alert(somevar1+ "" + somevar2);
    }

}(jQuery));

function atest2(somevar1, somevar2)
{
    test(somevar1+ "" + somevar2);
}

when executing test2 function the result is:

ReferenceError: test is not defined

My question is:

How can I call test2 to execute correctly jQuery's inner test function?

Thanks

2
  • 3
    You will have to define test outside of the anonymous function. Commented Feb 17, 2012 at 20:55
  • 1
    You can define test() outside of the jQuery load function, and still use it from within. Commented Feb 17, 2012 at 20:55

5 Answers 5

2

test is only defined in the anonymous function wrapped around it.

For the most part, function definitions should ALWAYS be outside of any anonymous functions. There are of course exceptions, but those only apply to people who know exactly what they're doing with closures.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to export test to the global scope if you want to use it outside the anonymous function. That can be done in ths way:

(function ($) {  
    // ...
    function test(somevar1, somevar2) {
        alert(somevar1+ "" + somevar2);
    }
    window.test = test; // <-- This
}(jQuery));

The big advantage of this method over moving the function declaration outside the anonymous function is that test can still use local variables, which are only accessible from within the anonymous function.

Comments

0

Look this is outside the onready function and then you can use it.

function test(somevar1, somevar2)
{
    alert(somevar1+ "" + somevar2);
}

(function ($) {  

    $(document).ready(function() { 
         test("hola","caracola");
    });

}(jQuery));

Comments

0

As stated by fellow members its clear that test function can be called if it is outside the anonymous function. This is necessary coz by defining test function inside anonymous function limit the scope of test function.Moreover, jquery is an awesome framwork for javascript , but after all its javascript so ne valid javascript snipplet wud work with jquery and vice-versa

Comments

0

you can call the function using apply, that is calling test from the callee

(function ($) {  

    $(document).ready(function() {
         test.apply(this,["hola","caracola"]);
    });

    function test(somevar1, somevar2)
    {
        alert(somevar1+ "" + somevar2);
    }

}(jQuery));

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.