I have the following piece of code:
function Obj() {
var container = [1, 2, 3];
this.callback_m = function() {
if (obj.exists(this)) {
//...
};
}
this.exists = function(element) {
return !(container.indexOf(element) == -1);
}
}
var obj = new Obj();
$(".elem").on('click', obj.callback_m);
I'm using an object's method as a callback function. It is obvious that when this method is called 'this' is set to the element for which the event was triggered. I'm passing 'this' element to the 'exists' method of an object to see if it's present in collection. However, to get to 'exists' method I need to reference 'obj' varible which references my object.
obj.exists(this)
But this is certainly a wrong choice since 'obj' can have different name or be out of scope. And I can't use bind() here either because I need the reference to the element the event was triggered for.
The only solution I came up with is to use closure to remember reference to itself. This is how it looks right now:
function Obj() {
var container = [1, 2, 3];
var self = this;
this.callback_m = function() {
if (self.exists(this)) {
//...
};
}
this.exists = function(element) {
return !(container.indexOf(element) == -1);
}
}
Is there any other solution to the problem and what are the potential problems with the apporoach I came up with?