JavaScript Patterns 4.4 Self-Defining Functions
2014-06-10 22:34 小郝(Kaibo Hao) 阅读(304) 评论(0) 编辑 收藏 举报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 function scareMe(); // 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 property scareMe.property = "properly";
// 2. assigning to a different name var prank = scareMe; // 3. using as a method var spooky = { boo: scareMe }; // calling with a new name prank(); // "Boo!" console.log(prank.property); // "properly" // calling as a method spooky.boo(); // "Boo!" console.log(spooky.boo.property); // "properly" // using the self-defined function scareMe(); // Double boo! console.log(scareMe.property); // undefined
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。