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, this will reference the groupList object inside the function, while in the second case, this will reference the global window object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With