JS--匿名函数

匿名函数的应用

  (1)将一个匿名函数保存在变量中

var sayName = function(){
    console.log('sayName function');
}

  (2)将一个匿名函数保存在对象的方法中

var person = {
    sayName: function(){
        console.log('sayName');
    }
}

 

  (3)将一个匿名函数作为回调函数

setTimeout(function(){
    console.log('hello world');
}, 1000);

 

函数作为对象可以动态的添加属性,针对这个功能我们可以在编写代码时有诸多技巧可用。

  (1)通过给函数添加一个属性并通过跟踪这个属性来达到跟踪函数的目的

var store = {
    nextId: 1,
    cache: {},  
    add: function(fn){
        if(!fn.id){
            fn.id = store.nextId++;
            return !!(store.cache[fn.id] = fun);    
        }
    }
}

  (2)通过记住先前的计算结果来避免重复的复杂计算,从而提高性能

function getElement(id){
    if(!getElement.cache){
        getElement.cache = {};   //创建一个缓存
    }
return getElement.cache[id] = document.getElementById(id) || getElement.cache[id];   
}
原文地址:https://www.cnblogs.com/marton/p/10269573.html