javascript - Is there any way to specify which 'this' I want to use in a JS anon function, similar to how Java does it? -


i've come across problem few times, , i'm wondering if can solved without having bind anon function 'this' in context of parent object.

here situation:

i have array-like object, lets call 'numline', implements 'each' method. contained within instance of object, lets call 'numtank'. current code looks this:

function numtank(numline) {     this.numline = numline; }; numtank.prototype.charforelem(elem) {     return "number: " + elem; } numtank.prototype.tostring() {     var str = "";     this.numline.each(function(elem) {         str += this.charforelem(elem); //but 'this' called in contex of 'numline' instance, dosen't (and shouldn't) have charforelem class.      });      return str; }  var tank = new numtank(arbatrarynumline); tank.tostring(); //uncaught referenceerror: charfromelem not defined in numline 

when ask 'similar how java it', mean how java allows prepend class name 'this' specify 'this' use.

is there anyway around without having bind anonomouns function this?

what done hold reference called self. common practice.

numtank.prototype.tostring() {   var self = this, str = "";   this.numline.each(function(elem) {     str += self.charforelem(elem);   });   return str; } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -