Because the second parameter of the on()
function is a function to be executed, not the result of a function execution.
This code:
element.on( 'click', function() {
thisAnimate(element);
});
Means, when the button is clicked, execute the anonymous function, which in turn executes the thisAnimate()
function and passes it the element
parameter. However, inside the anonymous function, this
refers to the element that raised the event. So if you want to pass it to the thisAnimate()
function, you should write:
element.on( 'click', function() {
thisAnimate(this);
});
Although in your code, you declared the element
variable at a higher scope, so it is accessible to the thisAnimate()
function without having to pass it in a parameter.
Similarly, this code:
element.on( 'click', thisAnimate);
Means, when the button is clicked, execute the thisAnimate()
function. It will be automatically passed the standard event parameters (e.g. event
). Inside the thisAnimate()
function, this
refers to the element that raised the event.
But this code:
element.on( 'click', thisAnimate(element));
Means, when the button is clicked, execute the returned value of the thisAnimate()
function. This obviously doesn't make any sense unless the thisAnimate()
function returns a function. For most cases, this is an error. Again, the element
variable is undefined.