Reputation: 185
I am trying to understand what is the difference between these two jQuery snippets as they will have the same result.
var method = {
myFunctionA: function() {
// do something
},
myFunctionB: function() {
// do something
},
}
$(selector1).click(function() { method.myFunctionA(this) });
$(selector2).click(function() { method.myFunctionB(this) });
function myFunctionA(){
// do something
}
function myFunctionB(){
// do something
}
$(selector1).click(myFunctionA);
$(selector2).click(myFunctionB);
Upvotes: 0
Views: 92
Reputation: 64923
Basically first approach uses an anonymous object and declares two methods, while second one uses procedural programming.
There's something to note too. You could do that this in the first sample:
var method = {
myFunctionA: function() {
// do something
},
myFunctionB: function() {
// do something
},
}
$(selector1).click(method.myFunctionA);
$(selector2).click(method.myFunctionB);
And method variable would be better called as "someObject", because it contains an object and it's that one that contains methods.
Maybe you need to learn basic concepts about object-oriented programming and JavaScript prototype-oriented programming.
Upvotes: 1
Reputation: 385144
In example #2, you are setting (as a jQuery event handler) a function reference. This reference refers to myFunctionA
(and another to its friend myFunctionB
).
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:
method.myFunctionA(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 this
to the ultimate destination of myFunctionA
. To add further insule, myFunctionA
doesn't even take a parameter, so it's complete wasted effort anyway.
Upvotes: 2