4

I have 3 line for the same consequence

  1. <button onclick="myFunction()">Click me</button>
  2. button.onclick=function(){alert('This is my test')};
  3. button.addEventListener("click", fuction(){alert('This is my test')});

Could you tell me the way is the best.

phuocph
  • 121
  • 1
  • 8

1 Answers1

5

I recommend method 3.

If you use the first method, one drawback is harder maintenance. If you were to change the function name, then you would need to change it within multiple files - the cause of many bugs.

Assuming that you're running your JavaScript after the DOM has loaded, I would (personally) define the function, then attach it to the button like so:

function buttonListener(event) 
// ...
button.addEventListener('click', buttonListener);

This way, your JavaScript stays in one file.

However, if you are executing as fast as possible (no DOM) or were coding in <script> tags within a relatively small markup file, then I see no issue with method one.

Try to avoid method 2 if you can - assigning a property to an anonymous function is slightly harder to read (and is somewhat implicit).

Jason Cemra
  • 563
  • 5
  • 15
  • `button.onclick = buttonListener` would work, so your argument against method 2 is invalid; however, method 3 is as you said the best and should be used – pwolaq Jun 10 '16 at 06:57