0

Possible Duplicate:
javascript syntax: function calls and using parenthesis

 t.onclick = doSomething 

 t.onclick = doSomething()

what's the different between the two event registrations?

sometimes I would confuse about them,add an parentheses seems would not cause big problem?

Community
  • 1
  • 1
hh54188
  • 14,887
  • 32
  • 113
  • 184

2 Answers2

8

The first one assigns a reference to doSomething to the onclick property. The second assigns the return value of doSomething. That's unlikely to be what you want, unless doSomething returns a function.

Assign a reference:

function doSomething() {
    console.log("something");
}
//When t is clicked, "something" is logged
t.onclick = doSomething;

Assign the return value:

function doSomething() {
    console.log("something");
}
//"something" is logged immediately. When clicked, nothing happens
t.onclick = doSomething();

Assign a returned function:

function doSomething() {
    return function() {
        console.log("something");
    };
}
//When t is clicked, "something" is logged
t.onclick = doSomething();
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • So `doSomething()` should be better named as `returnSomethingNowWhichWillDoSomethingThen()` ;-) – A.H. Feb 20 '12 at 13:02
0

The manner in which you reference objects means a lot in JS. There's a difference between doSomething; and doSomething(); because the first is referencing the function and the latter is referencing the return value of the function. Let's look at this example and you'll see what I mean. doSomething(); not only invokes the function but returns the return value of the function:

function doSomething() {
    return 5;
}

console.log(doSomething); // function() { return 5; }

console.log(doSomething()); // 5

So doing t.onclick = doSomething; is very much like saying t.onclick = function() { return 5; };

David G
  • 94,763
  • 41
  • 167
  • 253