JavaScript's Function Factories

我想請問大家,當我學緊 JavaScript 時, syntax 好似同其他 language 好唔同,example as following:
  1. function averageFactory() {
  2.     var sum = 0;
  3.     var count = 0;
  4.     return function (value) {
  5.         sum += value;
  6.         count++;
  7.         return sum/count;
  8.     };
  9. }

  10. Example usage:
  11. var avg = averageFactory();
  12. avg(1); (result is 1)
  13. avg(3); (result is 2;
A function is embedded within another function, is this called "Higher order function"?? Does  anyone know more background regarding this?

我想請問大家,當我學緊 JavaScript 時, syntax 好似同其他 language 好唔同,example as following:A fun ...
ronstudio 發表於 2015-5-17 19:41

no, this is called first class function
function = object
it is just passing an object/ function back


回覆 2# snoopy11hk

    the capability of assigning function to a lvalue makes functions first-class citizen. but embedding a function into another function definition is called "closure". In this case the function is defined in a function scope, but the parent function exports (returns) the embedded function so that the embedded function can be accessed or called from the global environment. There are a few advantages of using closure, but those are all advanced use. If you wanna know more, I can probably give you some reference.


one of the most useful example is following
function print(num)

for(var i = 0; i < 3; ++i)
    }, 1000);

will give you three lines of "3" a second later
because the inner function (which contains a console.log line only) get the value of i by remember the address of i.

however, if you write the function in the loop as
    return function()
}(i), 1000);

this will give you the desired three lines of 0, 1, 2, a second later. As the inner function is called immediately with the i at that moment.

you can learn more from here


Thanks for the help. I'll research more regarding the closure. This lexical scoping really uncommon to me.


本帖最後由 chi251155 於 2015-5-18 00:13 編輯

回覆 5# ronstudio
It is hard to understand at first but you will get better with more practices and readings js codes from others


回覆  snoopy11hk

    the capability of assigning function to a lvalue makes functions first-class ...
chi251155 發表於 2015-5-17 23:06

thanks for ur rectification


function return another  function?!!


回覆 8# fhleung



回覆 9# dvd-rw

From Wikipedia:
In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:
- takes one or more functions as an input
- outputs a function

所以樓主既例子都係一個higher order function(因為佢outputs a function)

而closure係講緊一個function會capture free variable
  1. function (value) {
  2.     sum += value;
  3.     count++;
  4.     return sum/count;
  5. }
裡面根本冇sum呢個variable既definition,所以sum係一個free variable
而sum既definition來自averageFactory,所以我地話呢個output function係一個closure,capture左sum呢個variable