Reputation: 632
I tried googling for the answer but the problem is I don't really know how to address the problem, i just find the wrong topics.
What's the difference between:
this.on('click',thisismyfunction );
and:
this.on('click', function(){
thisismyfunction();
});
Upvotes: 2
Views: 103
Reputation: 1708
One is a named function. The point of that is that you may be calling the function from multiple places, multiple times. The other is an annonomous function. It basically is like saying "do the following:"
Functions: A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows:
function named(){ // do some stuff here }
An anonymous function can be defined in similar way as a normal function but it would not have any name.
A anonymous function can be assigned to a variable or passed to a method as shown below.
var handler = function (){ // do some stuff here }
JQuery makes a use of anonymous functions very frequently as follows:
$(document).ready(function(){ // do some stuff here });
As taken from TutorialsPoint jQuery Basics
Upvotes: 2
Reputation: 10728
In your example there is probably no difference to the outcome. But the two methods do behave slightly differently:
First example:
this
inside your function refers to the clicked on elementSecond Example
this
inside your function refers to the anonymous functionSo which style you use depends on your own preferences and what you want to achieve
Upvotes: 0
Reputation: 71939
One notable difference: the first function will be directly passed an event object, accessible by whatever you name the first argument of thisismyfunction
, or at arguments[0]
. In the second version, that object will be passed to the outer anonymous function.
Also, on both examples nothing is called right away. You're binding both functions (your named function in the first case, or the anonymous function in the second case) as event handlers, so they will be invoked after the related event occurs.
Which one you use will depend mostly on code structure and style. As bennett_an said, it's preferable to use the first variation when you're binding the same function to multiple events.
Upvotes: 3
Reputation: 6968
thisismyfunction will recieve no arguments. the way you have it embed in the anonymous function.
Upvotes: 0
Reputation: 91716
Really nothing.
The first example will bind to thisismyfunction
directly. The second example will bind to an anonymous function that then calls thisismyfunction()
when called.
Upvotes: 1