0

I have some code:

$(function(){
    function foo() {
     var elem = $('.some-dom-elem');
     console.log(elem);
    }

    location.reload = function() {
     foo(); // returns undefined
    }
});

And here is the same code with the addition of an extra jQuery ready function:

$(function(){
    function foo() {
        var elem = $('.some-dom-elem');
        console.log(elem);
    }

    location.reload = function() {
        $(function(){
            foo(); // returns DOM element
        });

    }
});

Why do I need the extra jQuery ready function in the second code sample in order to make my foo function not return undefined?

  • Possible duplicate of [When should I use jQuery's document.ready function?](https://stackoverflow.com/questions/13062246/when-should-i-use-jquerys-document-ready-function) – johnny243 Sep 26 '19 at 14:18
  • 2
    Your `foo` function doesn't return anything. Try adding `return elem` to it. – phuzi Sep 26 '19 at 14:19
  • 2
    Who tells you you should? And why rewrite location.reload (assuming you can) – mplungjan Sep 26 '19 at 14:19
  • 1
    Assigning `location.reload` to a function is a very odd thing to be doing - assuming it's not already throwing an error – Rory McCrossan Sep 26 '19 at 14:28
  • 1
    Simple answer. You don't. – Taplar Sep 26 '19 at 14:28
  • 1
    Just out of curiosity, I opened my console on SO and tried to reassign the reload method. Didn't log an error. Hit F5, my logic did not happen and the page reloaded. Doesn't seem like this is a valid thing to do. – Taplar Sep 26 '19 at 14:31

0 Answers0