Why does the self-defining function assignment continue to point to an old function

I find this example in “javascript design templates” and are confused with the behavior of the following code

this code creates a self-defining function:

var scareMe = function () { alert("Boo!"); scareMe = function () { alert("Double boo!"); }; }; 

now we refer to it with another variable

 var prank = scareMe; 

The confusing part is when I called the prank, it should update scareMe, and when I call it back, it should warn "Double boo", right?

but the result

 prank(); // "Boo!" prank(); // "Boo!" 

and if I check the scareMe function, then it was overridden.

 scareMe(); // Double boo! 

prank is just a reference to scareMe, than why is there a difference?

+4
source share
3 answers

prank points to the original function, not to scareMe .

Take a look at this example:

 var scareMe = 1; var prank = scareMe; scareMe = 2; 

You do not expect a change to scareMe change prank , right? It exactly matches the functions.

 var scareMe = function() { alert( 'Boo' ); }; var prank = scareMe; scareMe = function() { alert( 'Double boo!' ); }; 

There is no difference between integers and functions in this regard. prank remains unchanged even when scareMe changes. The fact that scareMe changes from within another function does not change this fact.

Confusion can arise from the way objects are commonly used. This does not replace the original function as often as you can change the properties of the object.

 var scareMe = { message: 'Boo' }; var prank = scareMe; scareMe.message = 'Double boo!'; alert( prank.message ); // alerts 'Double boo!' 

This is not what you do with the functions in the original example. Changing a variable pointing to a completely different function does not change the reference to the function in another variable.

+5
source

prank not a reference to scareMe (this is not possible in javascript), it is a reference to a function object. 2 variables independently refer to the same function.

The function explicitly overwrites everything that scareMe points scareMe . This has no effect on prank .

Look at this:

 scareMe = function() { alert("Double boo!"); }; 

There is nothing magical about this; it reassigns the nearest scareMe variable, which is global. He does not do anything.

+6
source

Result of scareMe(); depends on the execution order.

If you call scareMe(); before prank(); then he will warn Boo! and assign a new scareMe function, so the next time scareMe(); call scareMe(); he will warn Double boo! .

In your case, this is the same, you call prank(); he will warn Boo! and assign a new scareMe function, so after that, if you call scareMe(); he will warn Double boo! .

+2
source

All Articles