javascript - Access this from callback inside member function -
this question has answer here:
i'm trying access class instance callback within member function. 1 example how like:
myclass.prototype.foo = function(){ var arr = [1, 2, 3]; arr.foreach(function(element){ //the next line doesn't work //becuase doesn't reference myclass-instance anymore this.elements.push(element); }); } here of course work loop (for(var = 0; < arr.length; i++) {...}) there situations can't.
i found 1 way access myclass instance:
myclass.prototype.foo = function(){ var arr = [1, 2, 3]; var mycurrentinstance = this; //store temporary reference arr.foreach(function(element){ //here works because use temporary reference mycurrentinstance.elements.push(element); }); } this doesn't seem clean me. there better way?
foreach has optional thisarg can pass after passing callback, should work:
myclass.prototype.foo = function(){ var arr = [1, 2, 3]; var mycurrentinstance = this; //store temporary reference arr.foreach(function(element){ //here works because use temporary reference this.elements.push(element); }, this); } heres function definition:
arr.foreach(callback[, thisarg]) heres documentation: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/foreach
update
you can use bind pass argument, though doesn;t prettier imho:
myclass.prototype.foo = function(){ var arr = [1, 2, 3]; var mycurrentinstance = this; //store temporary reference var myfunc = function(element){ //here works because use temporary reference this.elements.push(element); }.bind(this); myfunc(); } (i know bad example, demonstrates binding does)
Comments
Post a Comment