javascript - How to open set this to any object in jquery? -
if have function this
function foo(a) { $(this).html(a); } var r = $("#hello");
and can't change function foo
, can call foo
using r
, such inside foo
, this
refer object selected r
?
i tried this
r.each(function(i, x) { foo(1); });
but did not work. this
referred window
object.
that's because when call function itself, this
set global object (or undefined
) unless function scope bound.
to use function way wanted, write this:
r.each(foo);
that pass function directly , ensure this
set same value if body of foo
inside of anonymous function.
if want pass additional parameters foo
not passed each
, have call using call
or apply
:
r.each(function() { foo.call(this, 1); });
Comments
Post a Comment