Once you assign a function object to a variable, you can define the function again by this variable, and even define itself again within a function:
var scareme = function () { alert ("Boo!"); Scareme = function () { alert ("Double boo!"); };};/ /Using the self-defining functionscareme (); Boo!scareme (); Double boo!
If you need to do something special at the first time a function is executed, you can use this pattern. However, if you assign this variable to another object or execute it as a method of an object, the pattern may fail, considering the following code:
1. Adding a new Propertyscareme.property = "properly";//2. assigning to a different Namevar prank = scareme;//3. Using as a methodvar spooky = { boo:scareme};//calling with a new Nameprank ();//"Boo!" Prank (); "Boo!" Console.log (Prank.property); "Properly"//calling as a Methodspooky.boo (); "Boo!" Spooky.boo (); "Boo!" Console.log (spooky.boo.property); "Properly"//using the self-defined functionscareme (); Double Boo!scareme (); Double Boo!console.log (Scareme.property); Undefined
The core of this pattern is that Secareme holds a reference to a function object, and this reference is modified in the original function object. So when the reference to the function object is assigned to another variable prank, the PARNK reference cannot be modified by Secareme, so the schema is invalidated. This also reflects the fact that the function in JavaScript is an object.
JavaScript Basics-Define your own functions