A self-defined function (also called a lazy function definition) when using a function declaration

In the book "JavaScript Templates" by Stoyan Stefanova there is a part about a self-defined function.

var scareMe = function(){ console.log("Boo!"); scareMe = function(){ console.log("Double Boo!"); } } scareMe();//==>Boo! scareMe();//==>Double Boo! 

It works as I expected. But I am modifying the scareMe function as follows:

 function scareMe(){ console.log("Boo!"); function scareMe(){ console.log("Double Boo!"); } } scareMe();//==>Boo! scareMe();//==>Boo! 

Problem :

  • what's the difference between them?
  • In the second case, why the output is not "Double Boo!", But "Boo!"
+6
source share
3 answers

The first scareMe function overwrites its own behavior when called, creating another scareMe function in it, which overwrites the one in the upper scope, so the definition of the original scareMe changes, I see that this approach was used if you want to do it the first time in the application and want to change its behavior immediately after setting it up.

If you have identified:

 var scareMe = function(){ console.log("Boo!"); var scareMe = function(){ //define it with var console.log("Double boo!"); } } scareMe();//==>Boo! scareMe();//==>Boo! //you will see the behavior as that of the second one. 

Also one practical implementation of a one-time installation:

 var scareMe = function(){ console.log("Boo!"); //I have done my job now. I am no longer needed. scareMe = undefined; } scareMe();//==>Boo! scareMe();//==> oops error 

In the second case, you create a new function called scareMe , whose scope is only inside the function, it is not overwritten.

Try this for example:

 function scareMe(){ console.log("Boo!"); function scareMe(){ console.log("Double bool!"); } scareMe(); //Now this invokes the once defined inside the scope of this function itself. } scareMe();//==>Boo! and Double bool! 
+9
source

In your first consent, scareMe is a global variable (in your context). When in "double boo" you change the value of this global variable, then it works. In the second agreement, the internal scareMe is a local variable and does not change the global value. So this is about the scope of variables.

+4
source

With the exception of lifting and debugging, you might consider:

 function f(/* ... */) { /* ... */ } 

To be equivalent:

 var f = function(/* ... */) { /* ... */ }; 

If we translate the second code sample to use this second form, we get:

 var scareMe = function() { console.log("Boo!"); var scareMe = function() { console.log("Double bool!"); }; }; 

Note that this is not the same as your first snippet; the definition of an internal function has var on it. With the inner var it creates a new variable called scareMe , which obscures the outer.

+2
source

Source: https://habr.com/ru/post/954908/


All Articles