Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why self defining function reference keeps pointing to the old function

Tags:

javascript

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?

like image 203
nitesh sharma Avatar asked Dec 11 '22 23:12

nitesh sharma


2 Answers

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.

like image 179
Esailija Avatar answered Feb 15 '23 10:02

Esailija


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.

like image 38
JJJ Avatar answered Feb 15 '23 10:02

JJJ