Why can't I run this callback just by passing its variable name, but can I wrap it in a function?

Just a question. In my current understanding, the following two pieces of code are identical, except for one enclosed in a function. Why does it work with method 1 but not method 2? What is the difference?

Method 1:

// Reset button
$('.reset').button({
    icons: {primary: 'ui-icon-closethick'}
}).click(function(){groupList.change()});

      

Method 2:

// Reset button
$('.reset').button({
    icons: {primary: 'ui-icon-closethick'}
}).click(groupList.change);

      

EDIT: JSFiddle: http://jsfiddle.net/B8YEa/2/ - Please note that clicking the "Two" button throws an error Uncaught TypeError: Object #<HTMLButtonElement> has no method 'on'

and "One" is just fine, as well as the actual selection change

+3


source to share


2 answers


The difference is that the first code calls the function as a method of the object, while the second code calls the function as an independent function.

In the first case, it this

will refer to the object groupList

inside the function, and in the second case, it this

will refer to the global object window

.

If you call a function defining it as an element of an object eg. obj.method();

, it will be called as a method. If you get a reference to a function and call it eg. var m = obj.method; m();

, then the method is no longer associated with the object.




Also, as Tilo pointed out, the first code will look for a method every time an event occurs, and the second code will look for a method once when the event is associated.

+4


source


If groupList.change

it doesn't exist yet, but is defined later (but before the user clicks), then there is a difference. The same if it is redefined later.

The first code resolves groupList.change

when a click occurs.



The second code resolves immediately groupList.change

.

+1


source







All Articles