Luman75
Luman75

Reputation: 908

System unique id of a function passed as a parameter (javascript)

This is probably not possible but maybe some of the stackoverflow geniuses can find a solution :)

W would like to have a function like this:

var myCrazyFunc;
myCrazyFunc = function (param1, callback) {
  var funcId;
  // I would like to get an Id of the function passed by callback 
  // which will be different for those two calls in example below
  funcId = getFuncId(callback);
  callback();
};
myCrazyFunc("param1", function () {
  dosomething1;
});
myCrazyFunc("param1", function () {
  dosomething2;
});

Please don't ask why I need that :) Simply it would simplify my code if that was possible.

Upvotes: 0

Views: 227

Answers (1)

patrick
patrick

Reputation: 6840

Here is the function I made:

var myCrazyFunc;

var latestID = 0;
var funcToID = {};

function getFuncId(f) {
  if (f in funcToID) {
    return funcToID[f];
  }

  funcToID[f] = ++latestID;

  return latestID;
}

myCrazyFunc = function(param1, callback) {
  var funcId;
  // I would like to get an Id of the function passed by callback 
  // which will be different for those two calls in example below
  funcId = getFuncId(callback);

  console.log(funcId);

  callback();           
};

myCrazyFunc("param1", function() {
  'a';
});

myCrazyFunc("param1", function() {
  'b';
});

this example would log:

1
2

I you run it with the same function code you get the same id, like here:

myCrazyFunc("param1", function() {
  'a';
});

myCrazyFunc("param1", function() {
  'a';
});

Ouput:

1
2

I hope that's ok.

Upvotes: 2

Related Questions