JavaScript Patterns 4.4 Self-Defining Functions

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

转载于:https://www.cnblogs.com/haokaibo/p/Self-Defining-Functions.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值