I know in the code below it will print out undefined
if I click on the button, because this.field
becomes within the context of the button and not Container
. My question is how can I access this.field
of Container
when this.func
is passed into another function, which is a different context scope 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? Because I'd rather define the methods outside the constructor so I won't clutter it.
function Container(){
var thisObj = this;
this.field = 'field';
$('button').click(function(){ console.log(thisObj.field) });
}
Pass the object reference in as the event data:
function Container(){
this.field = 'field';
$('button').click(this, this.func);
}
Container.prototype.func = function(e){
console.log(e.data.field);
}
See here: http://jsfiddle.net/gilly3/nwtqJ/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With