函数 传统fibonacci函数:
1 2 3 4 5 6 7 var fibonacci = function (n ){ return n < 2 ? n : fibonacci (n - 1 ) + fibonacci (n -2 ); } for (var i = 0 ; i <= 10 ; i++){ document .writeln ('//' + i + ':' + fibonacci (i)); }
上述操作中fibonacci函数被调用了453次,我们调用了11次,它自身滴啊用了442次去计算可能已被计算过的值。增减函数记忆功能后,可以显著减少运算量。
1 2 3 4 5 6 7 8 9 10 11 12 var fibonacci = function (n ){ var memo = [0 , 1 ]; var fib = function (n ){ var result = memo[n]; if (typeof result !== 'number' ){ result = fib (n-1 ) + fib (n-2 ); memo[n] = result; } return result; } return fib; }
推而广之,memoizer函数取得一个初始的memo数组和formula函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var memoizer = function (memo, formula ){ var recur = function (n ){ var result = memo[n]; if (typeof result !=='number' ){ result = formula (recur, n); memo[n] = result; } return result; } return recur; } var fibonacci = memoizer ([0 , 1 ], function (recur, n ){ return recur (n - 1 ) + recur (n - 2 ); }) var factorial = memoizer ([1 ,1 ], function (recur, n ){ return n * recur (n - 1 ); })
继承 通过隐藏无谓的prototype操作细节,一行语句构造对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 var Mammal = function (name ){ this .name = name; } Mammal .prototype .get_name = function ( ){ return this .name ; } Mammal .prototype .says = funtion ( ){ return this .saying ||'' ; } Function .method ('inherits' , function (Parent ){ this .prototype = new Parent (); return this ; }) var Cat = function (name ){ this .name = name; this .saying = 'meow' ; } .inherits (Mammal ) .method ('purr' , function (n ){ ..... }) .method ('get_name' , function ( ){ ...... })