If you create a new function and assign it to the same variable that already holds another function, you’re overwriting the old function with the new one.
var scareMe = function () { alert("Boo!"); scareMe = function () { alert("Double boo!"); };};// using the self-defining functionscareMe(); // Boo!scareMe(); // Double boo!
This pattern(lazy function definition) is useful when your function has some initial PReparatory work to do and it needs to do it only once.
A drawback of the pattern is that any properties you’ve previously added to the original function will be lost when it redefines itself.
If the function is used with a different name, for example, assigned to a different variable or used as a method of an object, then the redefinition part will never happen and the original function body will be executed.
// 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!"console.log(prank.property); // "properly"// calling as a methodspooky.boo(); // "Boo!"console.log(spooky.boo.property); // "properly"// using the self-defined functionscareMe(); // Double boo!console.log(scareMe.property); // undefined
新闻热点
疑难解答