0

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);
1
  • 2
    Despite the passing use of the jQuery function $, this is really a Javascript question. Commented Jun 19, 2011 at 11:10

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.