3

I've created an object obj:

function a(id, ...){
   this.id = id;
   ......
}

var obj = new a("#somediv", ...);

and I have this function:

a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    });

};

Apparently, the this in the mouseover function points to the span instead of obj...

I know I can solve this problem by creating a variable and getting the property of this.id but

is there a way to make the this in the mouseover function point to obj instead?

1
  • 1
    Note that JS doesn't have pointers, at least not in the traditional sense that, e.g., C does. (You can't do any kind of pointer arithmetic, you can pass references as params but can't update which object the original variable referred to, etc.) Commented Jul 8, 2012 at 2:48

2 Answers 2

5

With pure JavaScript in newer browsers, you can bind the function:

a.prototype.b = function(){
    $(this.id+" span").mouseover(function(){
        $(this.id).addClass("c");
    }.bind(this));
};

With jQuery, you can get better browser support:

a.prototype.b = function(){
    $(this.id+" span").mouseover($.proxy(function(){
        $(this.id).addClass("c");
    }, this));
};
Sign up to request clarification or add additional context in comments.

1 Comment

As a note about bind vs proxy, foo.bind(bar) !== foo.bind(bar) which means that you'll need to store a reference to the bound function if you want to remove the event handler, however if you use jQuery's $.proxy, jQuery is able to unbind "identical" proxies of a function ($.proxy(foo, bar) !== $.proxy(foo, bar), however the returned function will have a GUID that jQuery can use to match proxies of the same function).
1

Alternative using $.proxy:

a.prototype.b = function(){
    $(this.id+" span").mouseover($.proxy(function(){
        $(this.id).addClass("c");
    }, this));
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.