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?
prank
is not a reference to scareMe
(this is impossible in javascript), it's a reference to the function object. The 2 variables are independently referring to the same function.
The function explicitly overwrites whatever scareMe
is pointing to. It does not affect prank
in any way.
Look at this:
scareMe = function() {
alert("Double boo!");
};
There is nothing magic about this, it will reassign the closest scareMe
variable, which happens to be the global one. It does not do anything else.
prank
points at the original function, not to scareMe
.
Look at this example:
var scareMe = 1;
var prank = scareMe;
scareMe = 2;
You don't expect that changing scareMe
would change prank
, right? It's exactly the same with 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
stays the same, even when scareMe
changes. That scareMe
is 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.
var scareMe = { message: 'Boo' };
var prank = scareMe;
scareMe.message = 'Double boo!';
alert( prank.message ); // alerts 'Double boo!'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With