记忆函数功能
使用JS记忆函数功能,能够有效提供代码的性能。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>记忆函数</title> 6 </head> 7 <body> 8 9 </body> 10 </html> 11 <script> 12 /** 13 * 记忆函数 14 * */ 15 function memoize(fn){ 16 return function(){ 17 var propertyName; 18 fn.storage = fn.storage || {}; 19 20 propertyName = Array.prototype.join.call(arguments,"|"); 21 22 if(propertyName in fn.storage){ 23 return fn.storage[propertyName]; 24 }else{ 25 fn.storage[propertyName] = fn.apply(this,arguments); 26 return fn.storage[propertyName]; 27 } 28 } 29 } 30 31 /** 32 * 计算阶乘的函数 33 * @param num 34 * @returns {number} 35 */ 36 function getFactorial(num){ 37 var result = 1, 38 index = 1; 39 for(;index <=num;index++){ 40 result *= index; 41 } 42 return result; 43 } 44 45 var calcFn = memoize(getFactorial); 46 debugger; 47 calcFn(5); 48 calcFn(5); 49 50 </script>