omega omega - 2 months ago 5
Javascript Question

How to open set this to any object in jquery?

In jquery, if I have a function like this

function foo(a) {
$(this).html(a);
}

var r = $("#hello");


and I can't change the function
foo
, what can I do to call
foo
using
r
, such that inside
foo
,
this
will refer to the object selected by
r
?

I tried this

r.each(function(i, x) {
foo(1);
});


but it did not work. The
this
referred to the
window
object.

Thanks

Answer

That's because when you call a function by itself, this will be set to the global object (or undefined) unless the function scope was previously bound.

To use the function the way you wanted, write it like this:

r.each(foo);

That will pass the function directly and ensure this is set to the same value as it would be if the body of foo was inside of your anonymous function.

If you want to pass additional parameters to foo which are not passed by each, you will have to call it using call or apply:

r.each(function() {
  foo.call(this, 1);
});
Comments