Prototypes and nested return functions, help! Prototypes and nested return functions, help! json json

Prototypes and nested return functions, help!


Lets break it down into it's parts

//create function API which is meant to be instantiated into an object using ///var foo = new API();function API(site, key, ...) {    this.site = site;    this.key = key;    this.schedule = new Scheduler(this);}//create two prototype functions on the API function called lookup & request//these two functions will be available as public functions on all //instantiated API objects and can be called like this//foo.lookup(resource, callback); / foo.request(url, callback);API.prototype = {    lookup: function(resource, callback) {        // build the url etc here        this.request(url, callback);    },    request: function(url, callback) {        // build a request here and send it        request.on('finished', function() {            callback();        });    }};//define function Schedulerfunction Scheduler(api) {     //when called, imidiately return a reference to an     //anonymous function that can be called later with     //the three arguments method, options & interval    return function(method, options, interval) {        // define a local variable id for this anonymous function        var id = null;        //create a private function inside the anonymous function call request        function request() {            //private function requests internals            api[method](options...);            id = setTimeout(function() {                request();            }, interval);        }        //when anonymous function is called return         //an object with a function called stop as property        return {            stop: function(attribute) {                clearTimeout(id);            }        }    }}

In the end you'd do something like this:

var foo = new API();var scheduler = foo.schedule('lookup', {some options object I presume}, some_interval);scheduler.stop();


how a return function can be inside another with variables that aren't defined anywhere or even passed to it!

And the Scheduler function just has me plain old baffled...

  1. http://eloquentjavascript.net/chapter3.html
  2. How do JavaScript closures work?