首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 4.4 Self-Defining Functions

2024-04-27 14:22:50
字体:
来源:转载
供稿:网友

javaScript Patterns 4.4 Self-Defining Functions

2014-06-10 22:34 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表