Is there any way to comparing function pointers in javascript? Basically, I want to see if I’ve added the same function multiple times to an array, and then only add it once. Yeah, I can program my way around it, but it would be much easier to do it this way.
The code below does NOT use an array, but illustrates the point I’m trying to make. I’d like for oldPointer to only be set if a myPointer is a different function.
Here is some example code:
function test()
{
}
test.prototype.Loaded = function()
{
this.loaded = true;
}
test.prototype.Add = function(myPointer)
{
if (this.oldPointer != myPointer) //never the same
{
this.oldPointer = myPointer;
}
}
test.prototype.run = function()
{
this.Add(this.Loaded.bind(this));
this.Add(this.Loaded.bind(this)); //this.oldPointer shouldn't be reassigned, but it is
}
var mytest = new test();
test.run();
Assuming bind is a function that uses Function.apply() to create a function closure binding
thisto the context,this.Loaded.bind(this)will produce a new function every time it is called. That is why your code does not work. Unfortunately there is no way to referencethis.Loadedfrom the function object produced by bind(), so comparison is impossible.If instead you did something like the below, your check would work, though I’m not sure how much use it would be to you.
Please clarify exactly what you are trying to do if you want a better answer.