Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 592
Charles Avatar asked May 27 '09 13:05

Charles


People also ask

How do you call a value in JavaScript?

Call by Value: Suppose there is a variable named “a”. Now, we store a primitive value(boolean, integer, float, etc) in the variable “a”. Let us store an integer value in “a”, Let a=5. Now the variable “a” stores 5 and has an address location where that primitive value sits in memory.

Can you assign a variable to a function JavaScript?

Programmers can create a single variable using the var, let, or const keywords and assign the function expression to that. However, creating a variable with the const keyword is recommended to assign the function as the function expression always remains constant.

What is JavaScript custom function?

Custom functions enable developers to add new functions to Excel by defining those functions in JavaScript as part of an add-in. Users within Excel can access custom functions just as they would any native function in Excel, such as SUM() .


1 Answers

Use apply call.

handleEvent.call(this, e);
like image 156
Patrick McElhaney Avatar answered Nov 08 '22 20:11

Patrick McElhaney