When calling a Javascript function, how do I set a custom value of "this"?

javascript, jquery, jquery-events, this

Solution

Use apply call.

handleEvent.call(this, e);

Problem

I'm using jQuery and I have a function that serves as an event callback, and so in that function "this" represents the object that that captured the event. However, there's an instance where I want to call the function explicitly from another function - how do I set what "this" will equal within the function in this case? For example: ``` function handleEvent(event) { $(this).removeClass("sad").addClass("happy"); } $("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked function differentEvent(event) { $("input.sad").keydown(e) { doSomeOtherProcessing(); handleEvent(e); // in this case, "this" will be the window object // but I'd like to set it to be, say, the input in question } } ```

Original source