0

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?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • I don't think it is. The problem in the topic you referenced was solved using simple .bind() function, whereas this solution is not what can be used here and I described why in my post. – Max Koretskyi Jul 20 '13 at 15:32
  • 1
    I don't think theres anything wrong with your pattern. Its actually pretty common. In any case, heres an SO question that asks/explains: http://stackoverflow.com/questions/4371333/is-var-self-this-a-bad-pattern – go-oleg Jul 20 '13 at 15:55
  • Ah. It was not clear to me that you still want `this` to reference the element. Personally I find it rather odd to use the functions of an object, but having `this` to refer something else than the object. Why don't you pass the element as argument to the function instead? – Felix Kling Jul 20 '13 at 17:52
  • I don't wan't 'this' to reference the element :). I am passsing the element to the function 'exists' using 'this' since it references the element. I want to have reference to my object. Maybe I didn't understand you, could you please provide piece of code? – Max Koretskyi Jul 20 '13 at 18:36

0 Answers0