Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access instance property in an instance method when the method is being passed into an another function?

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) });
}
like image 255
Tri Noensie Avatar asked Oct 11 '22 03:10

Tri Noensie


1 Answers

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/

like image 171
gilly3 Avatar answered Oct 31 '22 20:10

gilly3