-4

Im trying to understand how the browser works if it has 2 document.ready functions within it.

Sample code: Here printtest() module has a alert statement within my first document.ready function and its been called below but I don't see any action..

$(document).ready(function(){
    function printtest(){
       alert('Hi')
    }


})

$(document).ready(function(){

    printtest()


})


http://jsfiddle.net/7FuLc/1/

Since it has 2 document.ready function, how does the browser registers this function?

user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 3
    this has nothing to do with the document ready function specifically, you simply defined a function in one place, then tried to use it in another where it isn't defined. – Kevin B May 05 '14 at 15:58
  • 1
    There's rarely any reason to wait to *define* a function until the document is ready unless you're doing it to avoid making the function global. – Kevin B May 05 '14 at 16:01

1 Answers1

0

That code will not work because because javascript function creates a new scope variable every time it is declared. See the following:

$(document).ready(function(){
    function printtest(){
       alert('Hi')
    }
})

$(document).ready(function(){
    printtest() // ReferenceError, printtest undefined
})

compare this to

function printtest(){
    alert('Hi')
}

$(document).ready(function(){
    printtest() // alerts 'Hi'
})

$(document).ready(function(){
    printtest() // alerts 'Hi'
})

This way, both $(document).ready(function(){}) understand what printtest is.


To solve your problem, here is the modified code,

var printtest;

$(document).ready(function(){
    printtest = function (){
       alert('Hi')
    }
})

$(document).ready(function(){
    printtest(); // alerts 'Hi'
})

Now this will work the way you intend it to be because you declare the variable outside the function. This is due to closure (closure is inner javascript function, meaning that any outside variable can be accessed inside the inner javascript function).

In conclusion, if you want a function that is accessible across different functions, declare it outside so that any other closure will be able to access it.

mcn
  • 711
  • 4
  • 9