Functions in JavaScript run at a certain scope. A lot of the time, if
the function isn't a part of some Object that scope defaults to the
window object. All JavaScript functions also have two functions that
allow you to redefine the scope of a function as you call it: apply and
call. apply takes 2 arguments: the new scope to call the function under
and an array of arguments to call the function with. call does the same
thing but instead of an array of arguments, you just supply the
arguments as additional arguments to that function call.
Example:
var scope = "Scope";
var arg = "Arg";
var fn = function(e) {
window.alert(this + " => " + e);
};
fn(arg); // alerts " => Arg"
fn.apply(scope,[arg]); // alerts "Scope => Arg"
fn.call(scope,arg); // alerts "Scope => Arg"
This allows you to redefine the this variable on the fly. Additionally,
the reason self is used rather than this in fn.apply(self) is because
'this' changes scope once you enter a new function. So inside the
anonymous function defined in the setTimeout call, the scope variable
'this' is likely to be the window object. So you have to save a
reference to the 'this' you want to use as a separate variable so it can
be referenced elsewhere: hence self = this followed by (inside the
anonymous function) fn.apply(self).
-blair
Daemach wrote:
> Yeah that worked. I'm not certain I understand why though :)
>
> It does make sense that the closure would actually have to be created inside
> the event handler but .apply(self) is a new one for me. What exactly is
> that doing?
>
>
> Blair Mitchelmore-2 wrote:
>> $(document).ready( function() {
>> var timer;
>> var fn = function(e) {
>> if (e && e.type == 'blur') {
>> if (timer)
>> window.clearTimeout(timer);
>> }
>> // Do stuff
>> alert(this.id);
>> }
>> $('#test').blur(fn).keyup(function() {
>> var self = this;
>> timer = window.setTimeout(function() {
>> fn.apply(self);
>> },2000);
>> }).keydown(function() {
>> if (timer) window.clearTimeout(timer);
>> });
>> });
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/