Starkers
Starkers

Reputation: 10541

Dealing with the `this` keyword in named methods

A pretty simple problem, but it's one I want to get your opinion on:

function return_this_normal(){
//    console.log($(this));
     $(this).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal()
   }
);

Now, the above script turns the '.normal' div's text red on hover. You might expect it to turn it to green, because it calls return_this_normal after it turns the text red and return_this_normal changes the css of this to green.

However, it doesn't because this in return_this_normal returns not the element, but the actual function itself how exists in the browser's memory ( or something like that ). Suffice to say, updating the css of this function as it were does nothing at all.

Now to get around this trouble, we could simple pass the .normal element to the return_this_normal() function as a parameter, but I'm just wondering if there is a standardized way to do this in jquery as passing an element to a named function seems like pretty common functionality .

http://jsfiddle.net/Ea5Rh/3/

Upvotes: 0

Views: 34

Answers (2)

Adil
Adil

Reputation: 148110

Pass this to return_this_normal as this is only available in handler of mouseover

Live Demo

/* Normal */
function return_this_normal(ob){
   // console.log($(this));
     $(ob).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal(this)
   }
);

You can also pass the this using .call()

Live Demo

/* Normal */
function return_this_normal(){
    console.log($(this));
     $(this).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal.call(this)
   }
);

Upvotes: 0

Nevett
Nevett

Reputation: 996

If you want to add a function to jQuery, so you can run $(element).my_function() then you can add it to the $.fn object. In that function, this is set as expected.

$.fn.return_this_normal = function(){
     return this.css('color','green');       
}

$('.normal').mouseover( function(){
        $(this).css('color','red');
        $(this).return_this_normal();
   }
);

Note I am returning from the function to support jQuery's chaining syntax.

Otherwise you should pass this as an argument to your function, which is a perfectly normal thing to do if the function isn't a member of that object.

Upvotes: 2

Related Questions