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:
- what's the difference between them?
- In the second case, why the output is not "Double Boo!", but "Boo!"
function init() { init = function() {}; /* ... */ };
And now as long as I'm only usinginit
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.