javascript - how should I bind this through a function? -
this question has reply here:
how access right `this` / context within callback? 4 answersi've code below:
function foo(){ $('div').each(function(){ //here $(this) refers selected div }); });
now, when phone call foo in setinterval $(this)
won't referring div of each() method:
setinterval(function(){ foo(); },5000);
i tried bind():
setinterval(function(){ foo(); }.bind(this),5000); //or bind(document.queryselectorall('div'))
i'm incorrectly referring div $(this)
really. should do?
here's proof i'm getting undefined:
assuming want code within each
callback have access whatever value this
has when setinterval
phone call made, code has 2 problems.
the first you're not bind
ing foo
itself. code
setinterval(function(){ foo(); }.bind(this),5000);
successfully binds this
anonymous function function() { foo(); }
. anonymous function makes direct phone call foo
, (in non-strict mode) sets this
phone call global object window
or global
, happens direct function call.
you need explicitly pass on anonymous function's this
foo
phone call within anonymous function call
or apply
:
setinterval(function(){ foo.call(this); }.bind(this),5000);
now foo
has right this
, need create this
value accessible within of each
callback. that, can consult how access right `this` / context within callback?, instruct store outer this
in variable. store this
within variable , utilize variable instead of this
within inner callback:
function foo() { var outer_this_from_foo = this; $('.rscontent').each(function(){ //here $(this) refers selected div //but outer_this_from_foo refers `this` value outside callback var fi = $('>.img-responsive', outer_this_from_foo); // instead of $('>.img-responsive', this) }); };
javascript jquery
No comments:
Post a Comment