1

Sorry for asking, but how do I access myFunction() from someFunction()?

<script>
$(document).ready(function() {
    // Get messages
    var myFunction = function() {
      // doSth.
    }

    // Make the initial call on page load.
    myFunction();
);

function someFunction() {
    // Call the function a second time 
    myFunction();  // Call fails!
}
</script>

4 Answers 4

4

You are scoping it to the anonymous function you are passing to the ready method. Just move the definition outside that function.

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

Comments

1

Its more then a scope issue. Yes, you are scoping it to the anonymous function but even if you make it global by removing the var like this:

$(document).ready(function() {
     // gets defined AFTER THE DOM IS READY
     myFunction = function() {
      // doSth.
     }
}

// is called BEFORE THE DOM IS READY
myFunction();

It STILL won't work, because myFunction hasn't been defined by the time you call someFunction. someFunction is running immediately before the document is ready, which is BEFORE myFunction is defined.

Both functions need to be either in the document ready block, or outside it. If you need to manipulate DOM elements, I'd recommend inside.

If someFunction is called for a handler, you can remove the var declaration from myFunction and it will work as expected, because this will put myFunction in the global scope.

2 Comments

someFunction does not run immediately. It is just a function declaration.
myFunction will not be created untill the document ready event is fired. The last call to myFunction is fired before the document ready event is fired so even if you declare it in the global namespace the call will fail
1

I don't think this will work because till the dom becomes ready and the document 'ready' event is fired the 'myFunction' function will not be created. The second call to 'myFunction' happens much before the 'myFunction' is created. This case will fail even if you create the function 'myFunction' in global namespace.

If you are not using any closure values inside your 'myFunction', you can move this function to global namespace. This will solve your ploblem. Ex:

var myFunction = function(){
    //Do somthing
}

$(document).ready(function(){
    myFunction();
});


myFunction()

Comments

0

I think you wont be able to call myfunction() with your current code. You will have to get that function() { var myfunction = ... }; out of document.ready(). Seperate the method, then you can call myFunction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.