javascript - Javsacript object reference from jquery callback -
this question has answer here:
- how “this” keyword work? 19 answers
say have code
var someclass= function(id){ this.id = guidgenerator(); this.htmlelement = jquery("#"+id); this.initclickhandler(); }; someclass.prototype = { initclickhandler: function(){ this.htmlelement.on("click",function(e){ //need reference object here //in way allow //this.clickhandler(); }); }, clickhandler: function(){ alert(this.id); } }; someclassinstance1 = new someclass("a"); someclassinstance2 = new someclass("b");
how can relevant instance of "someclass" on "on "callback ?
need reference object here in way allow this
use variable keep reference this
:
someclass.prototype = { initclickhandler: function() { var me = this; this.htmlelement.on("click", function(e) { me.clickhandler(); }); }, clickhandler: function() { alert(this.id); } };
in case can bind context wbith: fun.bind(thisarg[, arg1[, arg2[, ...]]])
:
this.htmlelement.on("click", this.clickhandler.bind(this));
also note it's recommended start instances lowercase:
var someclassinstance1 = new someclass("a"); var someclassinstance2 = new someclass("b");
Comments
Post a Comment