0

Is it possible to call a javascript function without paranthesis? (). In the below code, from a book, has the line,

http.onreadystatechange = useHttpResponse;

If there is no paramenters in the function definition, can we call without arguments?

function getServerText() {
  var myurl = 'ajax.php';
  myRand = parseInt(Math.random() * 999999999999999);
  var modurl = myurl + "?rand=" + myRand;
  http.open("GET", modurl, true);
  http.onreadystatechange = useHttpResponse;
  http.send(null);
}


function useHttpResponse() {
  if (http.readyState == 4) {
    if (http.status == 200) {
      var mytext = http.responseText;
      document.getElementById('myPageElement')
        .innerHTML = mytext;
    }
  } else {
    document.getElementById('myPageElement')
      .innerHTML = "";
  }
}
2
  • 2
    The only situation where you can omit parenthesis is when using the new keyword. Or you use something hacky like setTimeout(func, 0), but that's not really reasonable IMO. edit: As Niet said, in this case you are not calling the function and you don't want to. You are assigning a function as callback so that other code can call the function later. Commented May 26, 2014 at 21:42
  • Here http.onreadystatechange = useHttpResponse is a reference to useHttpResponse function. You can do it partly because functions are first class objects in JavaScript. You can assign a function to a variable: var square = function(x) { return x*x; }. You can even have an array of functions: var fs = [square, function(x) { return x*x*x; }] You might find it interesting that yes you can invoke a function with a syntax like this: square.apply(null, [5]). Notice how I'm calling apply function on square function. Commented May 26, 2014 at 21:50

2 Answers 2

3

When assigning an event handler, you don't want to call the function, you're giving it a reference to a function, which will be called later.

So... no. () is used to mean "call this function", in this case with no arguments.

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

Comments

0

It is the same way of :

function add2values(a, b) {
  return a + b
}

const objX = { name: 'xyz', myAdd: null }

objX.myAdd = add2values

console.log( objX.myAdd(1, 2) ) // -> 3

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.