Question

I am having a hard time figuring out how to reassign a variable to a new function.

I have two anonymous functions that are assigned to variables and I want "first" to assign itself to "after" after it is called once.

When using .toSource in Firefox it seems like it is definitely reassigning first to after, but the "first in the click handler is still referencing or calling the first that was created at runtime.

Why is this?

JS

var after = function() {
    alert("AFTER");
}

var first = function() {
    alert("FIRST");
    //alert(first.toSource());
    first = after;
}

$(".order").click( first );

HTML

<button type="button" class="order">Order</button>

http://jsfiddle.net/E2R2R/2/

Was it helpful?

Solution

Following up on @MichaelGeary s answer, if you want to make the function work by referencing like that, put your function call inside an anonymous function:

$(".order").click( function() {
    first();    
});

Demo: http://jsfiddle.net/E2R2R/4/

OTHER TIPS

When you make this call:

$(".order").click( first );

you are using the value of first at the time of this call. Its value at that time is what is passed into the click() function.

Changing the value of the first variable later won't affect this.

Another way to look at it: think about the code inside jQuery's click() method. It doesn't know that you used the first variable in your call. The only information it has is the function that first refers to at the time of the call.

See @tymeJV's answer for a way to do what you want. Note what's different about it: the function you're passing into .click() (the anonymous function) doesn't have to change. When that function calls first(), it always uses the current value of that name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top