2

we use () to invoke the function, But I am confused why we use only function name when we attached function in onclick event in javascript.

function a(){
alert(0)
}

document.getElementById('btn').onclick=a


<input value="click" type="button" id="btn" />
11mb
  • 1,339
  • 2
  • 16
  • 33
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • 2
    There is a good explanation here: http://stackoverflow.com/questions/19732275/understanding-javascript-function-call-and-referance – William Price May 14 '14 at 03:53
  • Function is an object as well, so you can refer to it. For example `console.log instanceof Object` == true – Damask May 14 '14 at 03:56

3 Answers3

9

Because a() executes the function, while a is a reference to the function. If you do console.log(a) you will see the code of the function

juvian
  • 15,875
  • 2
  • 37
  • 38
6

Because we don't want to call the function at that moment, we just want to assign a reference to it to the property, so that it can be called later on when the event happens.

This would be incorrect:

document.getElementById('btn').onclick = a();

It would call the function immediately and assign the return value to onclick, which is undefined. So nothing would happen when the event takes place.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0
var a = function () {
    alert(0);
};

document.getElementById('btn').onclick = a

So you can call the function as above method .Assign function to a variable and calling it from anywhere

DEMO

underscore
  • 6,495
  • 6
  • 39
  • 78