自定义函数

自定义函数:

如果创建了一个新函数并且将其分配给保存了另外一个函数的同一个变量,那么就以一个新函数覆盖了久函数。在某种程度上,回收了旧函的指针以指向一个新的函数。而这一切发生旧函数体的内部。在这种情况下,该函数有一个新的实现覆盖并重新定义了自身。

var me=function(){
    console.log("bingo");
    me=function(){
        console.log(" twice bingo");
    }
}
me();
me();

优点:当函数有一些初始化准备工作要做,并且仅需要执行一次,那么这种模式就非常有用,因为不用执行重复的工作,即该函数的一部分可能并不再需要去执行。在这种情况下,自定义函数可以更新自身的实现,使用此模式可以显著地提升应用程序的性能,这是由于重新定义的函数仅执行了更少的工作。

缺点:当它重定义自身时已经添加原始函数的任何属性都会丢失。如果该函数使用了不同的名称,比如分配给不同的变量或者以对象的方法来使用,那么重定义部分将不会发生,并且将会执行原始函数。下面会给出实例。

 

//分配给不同的变量

var me=function(){
    console.log("bingo");
    me=function(){
        console.log(" twice bingo");
    }
}
me.property='myProperty';
var other=me;
var obj={
   another:me
};
other(); //bingo
other(); //bingo
console.log( other.property);  //myProperty
me();   //twice bingo
me();   //twice bingo
console.log(me.property);      //undefined ( 后面会解释原因

//作为一个方法来调用

var me=function(){
    console.log("bingo");
    me=function(){
        console.log(" twice bingo");
    }
}
me.property='myProperty';
var other=me;
var obj={
   another:me
};
obj.another();  //bingo
obj.another();  //bingo
console.log(obj.another.property);  //myProperty
me();           // twice bingo
me();           // twice bingo
console.log(me.property);           //undefined

当将一个新的变量时,如预期的一样,函数的自定义并没有发生。.每次当调用other()时,它都通知“bingo”,同时还覆盖了全局me函数,但other()自身保持可见旧函数,其中包括属性。当以obj对象的another()方法使用时发生了同样情况。

所有这些调用不断重写me()指针,以至于当它最终被调用时,它才第一次具有更新函数主体并通知"twice bingo"消息的权利,但它不能访问me.property属性。

 

posted @ 2016-02-03 11:30  秋虹连宇  阅读(173)  评论(0编辑  收藏  举报