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

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) }); } 
+4
source share
3 answers

Pass the object reference as 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/

+1
source

How to skip anonymous function?

 function Container(){ this.field = 'field'; var self = this; $('button').click(function() { self.func() }); } 

You don't have many options here ...

jQuery makes this a little easier for you and offers $.proxy :

  $('button').click($.proxy(this.func, this)); // or $('button').click($.proxy(this, 'func')); 
+2
source

I would like to point out that, generally speaking, you should avoid thinking of the variable 'this' as being similar to the one in java. You clearly understand this, but it is always repeated. Since javascript always points to the object you called the function on, your passing the instance function to another object used as its onclick is confusing. I don’t know what you intend to do in the instance method itself, but there is no reason why the onclick handler should be an instance method of another object. If it has access to the members you need, they are publicly available, so there is no need to use the instance method. If the work being done refers exclusively to the Container object, then onclick can be a separate function that will refer to the container and call the instance method.

0
source

All Articles