ZK Zhao
ZK Zhao

Reputation: 21583

javascript: What is the difference between anonymous function and declared function?

This is the jsFiddle: http://jsfiddle.net/CGAb7/

$( ".tweet1" ).click(function() {
    alert( "this is tweet1" );
});  

$('.tweet2').click(tryAlert());
  function tryAlert(){
    alert('this is tweet2');
  }

Why is the second version(declared function) get run automatically?

Upvotes: 0

Views: 37

Answers (1)

tymeJV
tymeJV

Reputation: 104795

In order to pass a function as a parameter, you omit the (), in your case:

$('.tweet2').click(tryAlert);

This allows the function to be called when needed. Adding () invokes the function immediately.

Upvotes: 5

Related Questions