I find this example in “javascript design patterns” and confused with the behavior of following code
this code creates a self defining function:
var scareMe = function () {
alert("Boo!");
scareMe = function () {
alert("Double boo!");
};
};
now we are referencing it to another variable
var prank = scareMe;
confusing part is when I called prank it should update scareMe and when i call it back it should alert “Double boo” isn’t it?
but the result is
prank(); // "Boo!"
prank(); // "Boo!"
and if I check scareMe function indeed it has been redefined.
scareMe(); // Double boo!
prank is just a reference to scareMe than why there is a difference?
prankpoints at the original function, not toscareMe.Look at this example:
You don’t expect that changing
scareMewould changeprank, right? It’s exactly the same with functions.There is no difference between integers and functions in this regard—
prankstays the same, even whenscareMechanges. ThatscareMeis changed from inside another function does not change this fact.The confusion might come from how objects are usually used. It’s not as common to mutate the original function as you might change an object’s properties.
This is not what you’re doing with functions in the original example. Changing a variable to point to a completely different function does not change the function reference in the other variable.