user495915
user495915

Reputation: 185

Javascript beginner syntax question

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);

Upvotes: 0

Views: 92

Answers (2)

Matías Fidemraizer
Matías Fidemraizer

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

Lightness Races in Orbit
Lightness Races in Orbit

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

Related Questions