3

How can I compare functions which were bounded before independently on context (this). I know that Function.prototype.bind returns new function but is it possible to find out reference to the original function? Let's say I want to implement function equalsOrigins to do it for me:

var func1 = someFunction.bind(obj1);
var func2 = someFunction.bind(obj2);
var func3 = otherFunction.bind(obj1);

func1 === func2; // naturally returns false
equalsOrigins(func1, func2); // should return true
equalsOrigins(func1, func3); // should return false
equalsOrigins(func2, func3); // should return false

Is that possible in javascript?

madox2
  • 49,493
  • 17
  • 99
  • 99
  • 2
    I will bite: why do you want this? – PeeHaa Dec 16 '15 at 13:10
  • To understand how it works :-) – madox2 Dec 16 '15 at 13:11
  • I'd be interested to see if this is possible, since getting the "original" would also mean getting the previous context, which, in a function nested in an object, could be interesting. – Rob Foley Dec 16 '15 at 13:13
  • 1
    Your best bet may be to compare `a.toString() === b.toString()`. The result of `Function.prototype.toString` is implementation-dependent but in most cases it returns the actual source code. That should pass your tests but obviously doesn't allow you to arbitrarily find a reference unless you keep track of all your functions somewhere and can compare against each until you find a match. – James Allardice Dec 16 '15 at 13:14
  • I think someone already answered this. please find below link http://stackoverflow.com/questions/9817629/how-do-i-compare-2-functions-in-javascript – Anshuk Dec 16 '15 at 13:16
  • @Annshuk no, that's not what I am asking. I don't want to compare source code – madox2 Dec 16 '15 at 13:22

1 Answers1

1

Is it possible to find out reference to the original function?

No, not without access to the engine internals or a debugger. The bound function does contain a reference to the target function, but it is not accessible.

Your best bet, if the function does not throw or return an object, might be to abuse it as a constructor, and reconstruct the reference from the prototype object.

function example() { /* sane */ }
var bound = example.bind({});

Object.getPrototypeOf(new bound).constructor == example // true
Bergi
  • 630,263
  • 148
  • 957
  • 1,375