7

In the "JavaScript Patterns" book by Stoyan Stefanov, there's a part about Self-Defining 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 modify the scareMe function as following:

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

 scareMe();//==>Boo!
 scareMe();//==>Boo!

Problem:

  1. what's the difference between them?
  2. In the second case, why the output is not "Double Boo!", but "Boo!"
5
  • This pattern is amazing. Besides obfuscation, is there any practical use ?? Sep 30, 2013 at 2:03
  • 1
    @GameAlchemist: Yes. Sometimes I have a function to do something that I only want to do once; initialization, say. I can define that function as so: function init() { init = function() {}; /* ... */ }; And now as long as I'm only using init by name and not actually capturing a reference to the original function, it will only initialize once. This could be done with a boolean variable, but this way you've got one less variable to keep track of.
    – icktoofay
    Sep 30, 2013 at 2:11
  • interesting. So for instance the rAF replacement by setInterval could become : requestAnimationFrame = function(cb) { requestAnimationFrame=function(){}; return setInterval(cb,16); }. A bit cryptic, but elegant. Sep 30, 2013 at 2:20
  • for the record you mistyped the name : it is Stoyan Stefanov, my friend google said. Sep 30, 2013 at 2:26
  • @GameAlchemist: in the book, the author also use this pattern to create Singleton pattern. function Singleton(){instance = this; Singleton = function(){return instance};}. Then When you create two instance, they are the same. var s1 = new Singleton(); var s2 = new Singleton(); console.log(s1 === s2);
    – jason
    Sep 30, 2013 at 8:52

3 Answers 3

11

The first scareMe function when invoked overwrite its own behavior by creating another function scareMe inside it, which overwrites the one in the upper scope, so the definition of original scareMe changes, i have see this approach been used if you want to do a first time set up in an application and want to change its behavior all over right after setting it up.

If you had defined:

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 setup:

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

   //I have done my job now. I am no longer needed.
    scareMe = undefined;

}

scareMe();//==>Boo!
scareMe();//==> oops error

Second Case you are creating a new function with the name scareMe whose scope is only within the function, it doesn't overwrite itself.

Try this one for instance:

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!
6
  • I don't think what you're calling hoisting is actually hoisting. I think you actually mean to say that they're modifying a closed-over variable.
    – icktoofay
    Sep 30, 2013 at 2:03
  • @user2782160: Your answer was actually rather different. I interpreted you as saying that you can't overwrite a function, which is false. You certainly can; it's just that in the second snippet, they aren't overwriting the function; they're shadowing it.
    – icktoofay
    Sep 30, 2013 at 2:05
  • @icktoofay not really what i meant is actual scareMe function is in global scope, and you define another function without var in the first example it gets hoisted to the global scrope which means it just overwrites the definition of first scareMe. See how it changes with thee first example in my answer.
    – PSL
    Sep 30, 2013 at 2:07
  • @PSL: I understand what you're saying, but I think you've got the terminology wrong. Hoisting is how JavaScript behaves as if all of the function definitions and variable declarations were moved to the start of the scope. That's not what you're describing as hoisting; what you're actually trying to say is that it's modifying a variable in an outer scope it closed over, which is not the same thing as hoisting.
    – icktoofay
    Sep 30, 2013 at 2:09
  • @icktoofay ahh yes right that's what i meant, it just modifies its own behavior due to lack of scope. Probably the wording is incorrect there.
    – PSL
    Sep 30, 2013 at 2:11
4

In your first approch, scareMe is a global variable (in your context). When in the "double boo", you change the value of that global variable, so it works. In the second approch, the inner scareMe is a local variable and it won't change value of the global one. So it's about the variable scope.

2

Except for hoisting and debuggability, you can consider:

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

To be equivalent to:

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

If we translate your 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 inner function definition has a var on it. With the inner var, it creates a new variable called scareMe that shadows the outer one.

3
  • 1
    in the second example, I don't think inner scareMe shadow the outer one, if so, the output will be "Double boo!", in fact, the output is "Boo!". I think Teddy is right.
    – jason
    Sep 30, 2013 at 9:25
  • @jason: Teddy is right, but when I say shadowing, I mean that you have two variables with the same name, and the innermost one hides the definition of the outermost one; I don't mean to say that the outer one is changed at all, just that it's hidden.
    – icktoofay
    Oct 1, 2013 at 2:56
  • yeah, I understand what you mean later, sorry:)
    – jason
    Oct 3, 2013 at 1:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.