I am trying to understand what is the difference between these two jQuery snippets as they will have the same result.
1
var method = {
myFunctionA: function() {
// do something
},
myFunctionB: function() {
// do something
},
}
$(selector1).click(function() { method.myFunctionA(this) });
$(selector2).click(function() { method.myFunctionB(this) });
2
function myFunctionA(){
// do something
}
function myFunctionB(){
// do something
}
$(selector1).click(myFunctionA);
$(selector2).click(myFunctionB);
In example #2, you are setting (as a jQuery event handler) a function reference. This reference refers to
myFunctionA(and another to its friendmyFunctionB).The function reference is passed a parameter — see the jQuery documentation for that.
In example #1, you are also setting (as a jQuery event handler) a function reference. This reference refers to an anonymous function, whose body looks like this:
Clearly it does the same thing, except for the function parameter; you’re discarding whatever parameter jQuery wanted to give you, and instead sending
thisto the ultimate destination ofmyFunctionA. To add further insule,myFunctionAdoesn’t even take a parameter, so it’s complete wasted effort anyway.