0

So I'm new to javascript/ajax to certain level, to my understanding that calling function at least the proper way to call a function is by also using the parenthesis but take the code snippet for example on the onreadystatechange event, that line is calling a function which brings me to my point when I add the parenthesis my ajax calls fail but when i remove it it works seemlessly, that is not the issue my question is why doesn't work with the parenthesis if functions are called with it?

if(xhr){
        xhr.onreadystatechange = showContent;
        xhr.open("GET", url_new_posts, true);
        xhr.send(null);
    }else{
        alert("Could not create XMLHttpRequest");
    }
Asta
  • 1,569
  • 13
  • 23
Prince
  • 65
  • 9
  • Where can i find the link to the question? – Prince Apr 27 '15 at 22:46
  • 1
    To answer your question, parentheses are not required when specifying a function in your `xhr.onreadystatechange` assignment above because you are not running the function right away. You are only telling the `xhr` object which function to call when the readystate changes. If you write `xhr.onreadystatechange=showContent();` you are actually executing the `showContent` function right away, then assigning its return value to `xhr.onreadystatechange` – Thriggle Apr 27 '15 at 22:53
  • Thanks a lot, so to clarify its also possible call a function without the parenthesis aside from the ajax point an it will be valid? – Prince Apr 27 '15 at 23:40
  • It's not possible to call (that is, execute) the function without parentheses, but it's possible to reference it or pass it around. Without parentheses, the name of the function is simply a variable representing the function. Consider this: `var myMethod = function(){alert("hello world");};` This creates a variable called `myMethod` and sets it equal to a function. If I want myMethod to execute, I can call it with parentheses (`myMethod();`) but I can also use `myMethod` as a variable representing the function itself. `var anotherVariable = myMethod; anotherVariable();` Does that make sense? – Thriggle Apr 28 '15 at 04:39

0 Answers0