Just a simple question. In my current understanding, the two following chunks of code are identical except one is 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/ – Note how clicking “Two” throws the error Uncaught TypeError: Object #<HTMLButtonElement> has no method 'on' and “One” is just fine, as well as the actual changing of the select
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,
thiswill reference thegroupListobject inside the function, while in the second case,thiswill reference the globalwindowobject.If you call a function specifying it as an object member, e.g.
obj.method();, it will be called as a method. If you get the reference to the function and call it, e.g.var m = obj.method; m();, then the method is’t connected to the object any more.Also, as Thilo pointed out, the first code will look up the method each time the event happens, while the second code will look up the method once when the event is bound.