I know that in the code below it will print undefined if I press a button, because this.field becomes in the context of the button, not the Container . My question is how can I access this.field Container when this.func is passed to a different function, which is a different scope of context than Container .
function Container(){ this.field = 'field'; $('button').click(this.func); } Container.prototype.func = function(){ console.log(this.field); }
I know I can do this, but is there a better way? Since I prefer to define methods outside the constructor, so I will not interfere with it.
function Container(){ var thisObj = this; this.field = 'field'; $('button').click(function(){ console.log(thisObj.field) }); }
source share