Code
Code

Reputation: 303

Calling a javascript function without arguments

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 = "";
  }
}

Upvotes: 0

Views: 2294

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22274

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

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

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.

Upvotes: 3

Related Questions