valvince
valvince

Reputation: 397

clone javascript function, closure scope

I have this closure :

function CFetchNextData(ofs, pag, fetchFunction) {
  var offset = ofs;
  var limit = pag;

  return function(options, cb) {
    //do stuff to create params
    fetchFunction(params, cb);
    offset += limit;
  };
}

I then create a variable this way:

var fetchInfo = CFetchNextData(0, 10, specificFetchFunction);
fetchInfo(options, myCB);

So that everytime I call fetchInfo, pagination is automatically set to the next set of data. That works great, althought I'd like to have multiple instance of : "fetchInfo", each one having its own scope.

var A = fetchInfo; // I'd like a clone with its own scope, not a copy
var B = fetchInfo; // I'd like a clone with its own scope, not a copy

I could do:

var A = new CFetchNextData(ofs, pag, fetchFunction);
var B = new CFetchNextData(ofs, pag, fetchFunction);

But obviously I would have to setup "ofs" and "pag" each time, whereas by cloning fetchInfo, I'd have a stable pagination, set only once and for good. Do you know how to achieve that ? Thanks in advance

Upvotes: 0

Views: 349

Answers (2)

KpTheConstructor
KpTheConstructor

Reputation: 3291

This may not answer all of your question but just to pitch in , you could try assigning your parameters to a default / fallback value which will allow you to avoid setting ofs and pag each declaration . Below is a prototype of what I came up with . Its using oop :

class CFetchNextData {
    constructor(ofs, pag){
    this.OFS = 1; //default value
      this.PAG = 10; //default value
    this.ofs = ofs;
    this.pag = pag;

        if(ofs == null || ofs == undefined){

            this.ofs = this.OFS;

        }

    if(pag = null || pag == undefined){

            this.pag = this.PAG;

        }

    }
  fetchInfo(){     
      var data =  this.ofs += this.pag;
      return data;
    }

}


var task1 = new CFetchNextData(); // Falls back to default values..
var task2 = new CFetchNextData(32,31); // Uses values from specified in args...

document.write(task1.fetchInfo() + "\n")
document.write(task2.fetchInfo())

Hope this helps...

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816482

There isn't a concept of cloning a function in JavaScript. You need to call CFetchNextData (or another function) multiple times if you want to create multiple closures.

You could have CFetchNextData return a factory function instead of returning the actual function. But I'm not sure that's really an improvement.

function CFetchNextDataFactory(ofs, pag, fetchFunction) {
  return function() {
      var offset = ofs;
      var limit = pag;

      return function(options, cb) {
        //do stuff to create params
        fetchFunction(params, cb);
        offset += limit;
      };
  };
}

var fetchInfoFactory = CFetchNextData(0, 10, specificFetchFunction);
var A = fetchInfoFactory();
var B = fetchInfoFactory();

Upvotes: 2

Related Questions