Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'this' pointer in jQuery

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 Answers

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));
};
like image 102
icktoofay Avatar answered Sep 17 '26 13:09

icktoofay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!