0

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/

2 Answers 2

5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe it is that easy. I don't know why I couldn't think of this.
5

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.

1 Comment

Thanks for the great explanation. I appreciate your help. I always like understanding the why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.