Skip to content Skip to sidebar Skip to footer

Using Jquery $(this) In A Function

Quick Description: I'm aware that using $(this) in a function won't work because it's not within the right scope. I've also seen other similar questions. I just still can't figure

Solution 1:

You have scope issues, this in the doStuff is window context.

Use proxy()

hoverInterval = setInterval($.proxy(doStuff,this), 250);

Solution 2:

You can explicitly pass this into doStuff:

setInterval(function() {
    doStuff(this);
}, 250);

And in doStuff you can do:

functiondoStuff(element) {
    ...
}

Or you can explicitly set the value of this for doStuff like so:

setInterval(function() {
    doStuff.call(this);
}, 250);

Then you can still use $(this) inside doStuff without changing any of its arguments. For more information on call, see Function.prototype.call and its friend Function.prototype.apply.

Post a Comment for "Using Jquery $(this) In A Function"